在使用io.connect()的JavaScript中的HTML页面中,有一种方法可以捕获任何" onsend"事件
我使用了很多" socket.send()"在不同的地方,我需要"分类"并记录它们,如果我能用类似" onsend"事件(比如socket.on(" message")当我收到东西时)......
我当然知道我可以在全局函数中执行此操作,但由于解决方案的编码方式需要大量重新编码才能执行此操作并且重新测试不是一种选择...
TIA!
答案 0 :(得分:0)
您正在使用socket.io的默认事件来发送和接收消息。
这意味着如果您从服务器向客户端发送消息,则使用
//On server side or server side
socket.send(someMessage);
//On another opposite side
socket.on("message", function(data){console.log(data);})
以上一种事件是在socket.io库中定义的内置事件。这就是他们的代码中的某个地方,如
//On server side or client side
socket.send = socket.emit("message", someMessage);
//On opposite side
socket.on("message", function(data){console.log(data);})
所以,通过这种方式,我总是定义我的自定义事件,例如
//register a custom events on socket using socket.on function
socket.on("clientSentAData", function(data){console.log(data);})
//Client knows that there is a kind of evnets known as "clientSentAData" in the server side
//So client emit an data using "clientSentAData" event.
socket.emit("clientSentAData", data);
我这样对待我的bla bla类消息/通知/数据。
更具体的例子
//Server code
//Server register the sendMeMusicFile event
socket.on("sendMeMusicFile", function(tileName){
console.log("Received client request file with title " + tileName);
socket.emit("takeYourMusicFile", theMusicFile);
console.log("Sent music file with title " + tileName);
});
//Client Code
//Ask for a music
socket.emit("sendMeMusicFile", "Just Give me a reason");
//Client register the takeYourMusicFile event
socket.on("takeYourMusicFile", function(theMusicFile){
console.log("Received music file with title " + theMusicFile.tile);
// player.play(theMusicFile)
});
答案 1 :(得分:0)
如果其他人正在寻找答案,我将发布我正在使用的解决方法,可能无法在所有情况下都起作用:
let socket = new WebSocket(wsUrl)
let original = socket.send
socket.send = (...args) => {
doSomethingOnSend()
return original.apply(socket, args)
}