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

标签 node.js reactjs websocket ws

我正在尝试使用 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/

相关文章:

node.js - 喜欢 Mongoose

javascript - 如何通过超时和监听器创造 future

node.js - 使用 npm package.json 脚本增加 Node 内存

javascript - 有没有办法用 javascript 建立到 IP 的 tcp 连接?

node.js - (没有接受的答案)如何使用 ffmpeg 或 opencv 将 2 个重叠视频合并为一个视频?

javascript - 如何在 Redis 中找到部分匹配值并在其已存在时进行更新?

html - 在 Tailwind CSS 中制作动画标签?

ios - 是否建议将 React Native 应用程序的核心逻辑托管在云中?

android - 从 Arduino 到 Android 的 Websocket : send integer instead of text

java - 监控应用方法