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?
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.
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.
send() should return a promise, that resolves when the message is successfully sent through the socket #4727.
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); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With