Skip to content

Instantly share code, notes, and snippets.

@ynwd
Last active January 27, 2022 01:33
Show Gist options
  • Save ynwd/296728502149e102d22aa6b8a7a17f64 to your computer and use it in GitHub Desktop.
Save ynwd/296728502149e102d22aa6b8a7a17f64 to your computer and use it in GitHub Desktop.
server & react client websocket
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
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)
}
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