【发布时间】:2023-03-18 01:01:01
【问题描述】:
我正在尝试使用本机 websockets 并在后端使用 ws 在客户端上侦听自定义事件。
我首先创建一个连接的客户端池。
import express from 'express'
import http from 'http'
import WebSocket from 'ws'
import { v4 as uuidv4 } from 'uuid'
import processes from './routes/process.js'
import { EventEmitter } from 'events'
// Express
const app = express()
// Initialize a simple http server
const server = http.createServer(app)
// Initialize the WebSocket server instance
const wss = new WebSocket.Server({ server })
let connections = {}
wss.on('connection', (socket) => {
socket.id = uuidv4()
connections[socket.id] = socket
socket.send(socket.id)
console.log(`Client connected ID: ${socket.id}`)
socket.on('close', () => {
delete connections[socket.id]
delete socket.id
})
})
在反应时我存储socketID
const [socketID, setSocketID] = useState('')
useEffect(() => {
const socket = new WebSocket('ws://localhost:4000')
socket.onmessage = (message) => setSocketID(message.data)
}, [])
然后我想做的是使用 socketID 向特定客户端发出消息,我使用来自 react 的 axios 将请求中的 socketID 发送到快速路由。
然后回到服务器我使用EventEmitter从路由中获取客户端ID,我省略了细节原因有点冗长,但此时服务器正确识别客户端,问题似乎与发送自定义事件。
connections[socketID].send('notify', 'Hello specific client')
在客户端我监听自定义的nofify 事件
useEffect(() => {
const socket = new WebSocket('ws://localhost:4000')
socket.onmessage = (message) => setSocketID(message.data)
// Set notify listener to notify this specific client only
socket.addEventListener('notify', (data) => {
// I am expecting 'Hello specific client'
console.log(data)
})
}, [])
当我检查反应开发工具时,我可以看到 socketID 正在接收“自定义事件”,并将 socketID 更改为单词 notify。很明显,ws 只是发送单词 notify,而不是作为自定义事件,而是作为普通消息,客户端接收为 onmessage 而不是 eventListener。
【问题讨论】:
标签: node.js reactjs websocket ws