客户端正在使用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
似乎仅适用于客户端。
如何捕获只发送一次的数据?
我觉得你把事情搞糊涂了。 “打开”,“WebSocket”,“关闭”它们都与连接的生命周期有关。 你在那里不会收到信息。
另一方面,“消息”是接收信息。
服务器上缺少消息事件:
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之上使用包装器,那么您的代码会更容易。 例如,我认为使用Socket.io,您可以发送一个对象,并且它将被您字符串化