websocket.send()参数

Amy*_*Amy 22 javascript send websocket

通常我们只将我们想要发送的数据作为websocket.send()方法的参数,但我想知道是否有其他参数,如IP,我们可以放在括号内.我们可以这样使用它:

websocket.send(ip, data);  // send data to this ip address
Run Code Online (Sandbox Code Playgroud)

或者我应该打电话给其他方法?

pim*_*vdb 43

据我了解,您希望服务器能够将消息从客户端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"
}));
Run Code Online (Sandbox Code Playgroud)

服务器:

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);
  }
});
Run Code Online (Sandbox Code Playgroud)