websocket.send()参数

时间:2012-06-24 22:04:57

标签: javascript websocket send

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

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

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

1 个答案:

答案 0 :(得分:38)

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