通常,我们只会在websocket.send()
方法的参数中放置想要发送的数据,但我想知道是否有其他类似IP的参数可以放在括号里。我们可以这样使用吗:
websocket.send(ip, data); // send data to this ip address
我应该调用其他的方法吗?
通常,我们只会在websocket.send()
方法的参数中放置想要发送的数据,但我想知道是否有其他类似IP的参数可以放在括号里。我们可以这样使用吗:
websocket.send(ip, data); // send data to this ip address
我应该调用其他的方法吗?
据我理解,您希望服务器能够将客户端1的消息发送给客户端2。由于WebSocket连接的两端必须有一端是服务器,所以您无法直接连接两个客户端。
以下是一些类似于伪代码的JavaScript:
客户端:
var websocket = new WebSocket("server address");
websocket.onmessage = function(str) {
console.log("Someone sent: ", str);
};
// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
id: "client1"
}));
// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
to: "client2",
data: "foo"
}));
服务器:
var clients = {};
server.on("data", function(client, str) {
var obj = JSON.parse(str);
if("id" in obj) {
// New client, add it to the id/client object
clients[obj.id] = client;
} else {
// Send data to the client requested
clients[obj.to].send(obj.data);
}
});
str
应该指代从客户端接收到的数据。我不知道你使用的是哪个库,所以你需要参考它的文档来查看如何获取数据。 - pimvdb
websocket = new WebSocket(addresss)
建立连接。.send
只有一个参数。 - pimvdbWebSocket
构造函数。那么,“服务器向特定IP地址发送数据”是什么意思呢?服务器可以将数据发送到连接到它的套接字之一——您可能不需要在服务器端编写特定的地址。 - pimvdb