Created
January 27, 2022 09:23
-
-
Save ynwd/0661c298e6ca7bf4f15386f0790b1316 to your computer and use it in GitHub Desktop.
node.js rest api and websocket server with react client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import useWebSocket, { ReadyState } from 'react-use-websocket' | |
function getStatus(readyState) { | |
const connectionStatus = { | |
[ReadyState.CONNECTING]: 'Connecting', | |
[ReadyState.OPEN]: 'Open', | |
[ReadyState.CLOSING]: 'Closing', | |
[ReadyState.CLOSED]: 'Closed', | |
[ReadyState.UNINSTANTIATED]: 'Uninstantiated', | |
}[readyState] | |
return connectionStatus | |
} | |
function App() { | |
const { lastMessage, readyState } = useWebSocket('ws://localhost:8000') | |
return ( | |
<div> | |
<p>The WebSocket is currently {getStatus(readyState)}</p> | |
{lastMessage ? <span>Last message: {lastMessage.data}</span> : null} | |
</div> | |
) | |
} | |
export default App |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const ws = require('ws') | |
// handle http request | |
const app = express() | |
app.get('/', (req, res) => { | |
res.send('hello world') | |
}) | |
const server = app.listen(8000) | |
// handle websocket | |
server.on('upgrade', upgrade) | |
const wss = new ws.Server({ noServer: true }) | |
wss.on('connection', connection) | |
function upgrade(request, socket, head) { | |
wss.handleUpgrade(request, socket, head, socket => { | |
wss.emit('connection', socket, request) | |
}) | |
} | |
function connection(ws) { | |
let count = 0 | |
setInterval(() => { | |
count = count + 1 | |
ws.send(JSON.stringify({ count })) | |
}, 100) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment