Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

websocket.send() parameter

Tags:

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?

like image 447
Ivy Avatar asked Jun 24 '12 22:06

Ivy


People also ask

When using WebSocket send () How do you know?

The only way to know the client received the webSocket message for sure is to have the client send your own custom message back to the server to indicate you received it and for you to wait for that message on the server. That's the ONLY end-to-end test that is guaranteed.

How do I send a WebSocket message?

To send a message through the WebSocket connection you call the send() method on your WebSocket instance; passing in the data you want to transfer. socket. send(data); You can send both text and binary data through a WebSocket.

What does WebSocket send return?

send() should return a promise, that resolves when the message is successfully sent through the socket #4727.


1 Answers

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);   } }); 
like image 169
pimvdb Avatar answered Sep 21 '22 11:09

pimvdb