gpt4 book ai didi

javascript - 使用 Websockets 调用特定函数?

转载 作者:行者123 更新时间:2023-12-03 11:52:11 25 4
gpt4 key购买 nike

我正在尝试使用 Heroku 部署应用程序,但我猜他们不允许使用 Socket.IO,所以我必须使用基本的 WebSockets。如何将数据发送到特定功能,例如

如果使用套接字,则为:

// Server
socket.on('testFunction', function(data) {
console.log(data);
});

// Client
socket.emit('testFunction', 'Hello!');

但是对于 Websockets,我在 google 上搜索到的只是

// Server
ws.onmessage = function(data) {};

// Client
ws.send('This is a string, what do I do with myself');

任何信息都会很棒。谢谢!

最佳答案

参见here一些文档和示例。

以下是 Socket.IO 示例的一些粗略等效项:

// Server
ws.onmessage = function(event) {
var msg = JSON.parse(event.data);
switch(msg.type) {
case "testFunction":
console.log(msg.text);
break;
}
};

// Client
ws.send(JSON.stringify({type: "testFunction", text: "Hello!"}));

关于javascript - 使用 Websockets 调用特定函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25777279/

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