Search code examples
javascriptwebsocketsend

websocket.send() parameter


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, data);  // send data to this ip address

Or I should call other methods?


Solution

  • 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.

    This is some pseudocodish 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);
      }
    });