Last active
January 27, 2022 01:33
-
-
Save ynwd/296728502149e102d22aa6b8a7a17f64 to your computer and use it in GitHub Desktop.
server & react client websocket
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') | |
const app = express() | |
app.get('/', function (req, res) { | |
res.send('hello world') | |
}) | |
const server = app.listen(3000) | |
const wss = new ws.Server({ noServer: true }) | |
wss.on('connection', connection) | |
server.on('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) | |
} |
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 { WebSocketServer } from 'ws' | |
const wss = new WebSocketServer({ port: 8000 }) | |
function connection(ws) { | |
let count = 0 | |
setInterval(() => { | |
count = count + 1 | |
ws.send(JSON.stringify({ count })) | |
}, 100) | |
} | |
wss.on('connection', connection) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment