开发者

Nodejs networking - realtime communication

I'm new to node.js and I want to ask a simple question about how it works.

I have used FMs in the past for client to client communication and real time applications. For example, for creating a collaborative application where you need to开发者_如何学运维 see what other users are doing. I want to explore that using NodeJS.

I have couple of questions:

1) How does NodeJs handle server-to-client communication? Is thee any way to push information to the client? or the client needs to be making requests constantly to the server to see if anything has changed?

2) Is there such thing like permanent connections between the server and the clients?

3) How Can be handle client-to-client communication (of course thru the server)?

Thanks in advance.


3) How Can be handle client-to-client communication (of course thru the server)?

A simple solution is to open a websocket between the server and each client :

[Client A] <==websocket==> [Server] <==websocket==> [Client B]

If you go with Socket.IO for example, it is very easy to do client-to-client communication this way.

When the server receives a message from one client, you just broadcast it to all clients or send it to one specific client depending on your use case.

Some example code using Socket.IO :

var socket = io.listen(server);
socket.on('connection', function(client) {
  client.on('message', function(msg) {
    broadcast(msg); // broadcast message to all clients
    // OR
    socket.clients[session_id].send(msg); // send message to one client
  });

  client.on('disconnect', function( ) {
    console.log('Client Disconnected.');
  });
});


Quite a lot of Node.js questions from you recently ;)

  1. As Toby already said, Node can do HTTP, TCP/UDP and Unix Sockets. When you establish a permanent connection, you can of course push data to the clients.

  2. Since you are talking about Browser based clients, there a numerous ways to achieve this. You could for example use WebSockets with a Flash fallback. In case you are not interested in the low level details and want a complete package, take a look at Socket.IO.

  3. WebSockets can't do this, Flash can't do it either as far as I know. So unless you want to enter Java/Silverlight land, you'll need to route the requests through your server.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜