Javascript websocket.send() 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11181577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:48:31  来源:igfitidea点击:

websocket.send() parameter

javascriptwebsocketsend

提问by Amy

Usually, we only put the data we want to send as websocket.send()method's parameter, but I want to know whether there are other parameters like IP that we can put inside the brackets. Can we use it this way:

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

websocket.send(ip, data);  // send data to this ip address

Or I should call other methods?

或者我应该调用其他方法?

回答by pimvdb

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

据我了解,您希望服务器能够将消息从客户端 1 发送到客户端 2。您不能直接连接两个客户端,因为 WebSocket 连接的两端之一需要是服务器。

This is some pseudocodish JavaScript:

这是一些伪代码 JavaScript:

Client:

客户:

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"
}));

Server:

服务器:

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);
  }
});