gpt4 book ai didi

node.js - 使用 ws 发送自定义事件

转载 作者:行者123 更新时间:2023-12-04 08:04:17 28 4
gpt4 key购买 nike

我正在尝试使用 native 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
})
})

然后在 React 上存储 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)
})
}, [])

当我检查 React 开发工具时,我可以看到 socketID 正在接收“自定义事件”并将 socketID 更改为单词 notify。很明显,ws 只是发送单词通知,而不是作为自定义事件,而是作为客户端接收的普通消息作为 onmessage 而不是 eventListener。

最佳答案

因为我在任何地方都找不到关于 ws 发送自定义事件的任何信息,所以我只使用了唯一的发送事件来做所有事情,我在消息中附加了一个事件字符串以了解触发了哪个事件。

不理想,但它有效。如果有人能想到更好的方法,请告诉我。

wss.on('connection', (socket) => {
socket.id = uuidv4()
connections[socket.id] = socket
socket.send(JSON.stringify({ event: 'ID', id: socket.id }))

console.log(`Client connected ID: ${socket.id}`)

socket.on('close', () => {
delete connections[socket.id]
delete socket.id
})
})

connections[socketID].send(
JSON.stringify({ event: 'notify', payload: 'Hello specific client')})
)
useEffect(() => {
const socket = new WebSocket('ws://localhost:4000')

socket.onmessage = (message) => {

const data = JSON.parse(message.data)

if (data.event === 'ID') {
setSocketID(data.id)
}

if (data.event === 'notify') {
console.log(data.payload)
}
}

}, [])

关于node.js - 使用 ws 发送自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66304155/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com