客户端正在使用once发送一些数据。但是我想在服务器端捕获OPEN事件...
客户端代码:
const ws = new WebSokcet('ws://localhost:7887');
ws.once('open', () => {
ws.send('TEST|1234\0')
})在服务器端,我尝试了以下命令,但从未触发过。
websocket.on('open', data => {
console.log("test");
});根据https://github.com/espruino/Espruino/issues/1227#issuecomment-325630041中的注释,open似乎是仅限客户端的。
如何捕获只发送一次的数据?
发布于 2020-06-20 18:46:28
我认为你在混淆事件。"open","websocket","close“,它们都与连接的生命周期有关。您将不会在那里收到信息。
另一方面,“消息”是接收信息。
服务器上缺少消息事件:
websocket.on('message', function (msg) {
console.log('test')
})编辑:回复评论中的扩展问题。基本上,您想要的是在websocket库之上构建一个协议,以启用身份验证或其他功能。如果你想自己实现它,那么你应该添加不同类型的消息。可以这样说:
websocket.on('mmessage', function (msg) {
try {
// JSON parse must always be try catch, since string might not be a json and async errors are really bad
const data = JSON.parse(msg.toString())
if (!('type' in data')) {
// We require type in property, probably go on the error route
throw new Error(...)
}
const type = data.type
if (type === AUTH) {
/// ....
} else if (type == MSG) {
const token = data.token
// check token, which is required in every message
}
} catch (e) {
// TODO log and probably return feedback to the client
}
})在客户端上,您将执行类似的操作:
ws.once('open', () => {
ws.send(JSON.stringify({type: AUTH, data: {pass: '1234', user: 'TEST'}}))
})如果你在websocket之上使用wrapper,那么你的代码就更简单了。我认为,以socket.io为例,您可以发送一个对象,然后它将由您进行字符串化
https://stackoverflow.com/questions/62484400
复制相似问题