Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  126] [ 6]  / answers: 1 / hits: 115517  / 12 Years ago, sun, june 24, 2012, 12:00:00

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?


More From » websocket

 Answers
9

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

[#84692] Saturday, June 23, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
billt

Total Points: 608
Total Questions: 100
Total Answers: 87

Location: Cape Verde
Member since Fri, Nov 27, 2020
4 Years ago
;