-2

I work to develop a chat app with android on node.js server.I made a simple chat app.But everyone gets involved in the same room.I want to make a chat between only two people.How can I do that? What information should I send to the server?such as sender_name,receiver_name,message as a json format.

-How can I to do list online-users?

-And How can I start a chat between only two people?

What are the requirements for it?

erginduran
  • 1,678
  • 5
  • 28
  • 51
  • 1
    > What information should I send to the server? - How do you think? > I want to make a chat between only two people - Then make it, the question is ambiguous. > -How can I to do list online-users? - you keep a list of online users on a server and pass it to the client when needed. – alandarev Aug 07 '14 at 08:41
  • how to keep a list of online users?. now I can send data (sender,message) but talking to anyone who connects to the server on a single screen.but I dont want this.When this is not the only two people have talked – erginduran Aug 07 '14 at 08:46
  • https://stackoverflow.com/a/65787883/3904109 : for full working solution – DragonFire Jan 19 '21 at 10:25

1 Answers1

2

This might help:

I'd recommend setting up namespaces for each room you have your chat in. I did something similar in my own code. Note: Rooms and namespaces are a little different from each other in socket.io itself (socket.io has both: http://socket.io/docs/rooms-and-namespaces/).

In the Server code:

I have a method under socket.on('connection') that is similar to

socket.on('groupConnect', function(group){
    var groupNsp = io.of('/' + group);
}

This essentially makes sure that a namespace is exists under the name of the desired one. It doesn't mess it up or reset the namespace when it is called again.

Then for receiving the messages:

socket.on('message', function(data){
    var msg = data.msg;
    var nsp = data.nsp;
    io.of(nsp).emit('message', msg);
}

You could also add the nsp to the data you have already and then just send the data again to the clients.

Then, in the client code:

var socketOut = io.connect('http://yourdomain:1337/');
var someGroupOrMethodToGetGroup;
socketOut.emit('groupConnect', someGroupOrMethodToGetGroup);
var nsp;
setTimeout(function(){
    socket = io.connect('http://yourdomain:1377/' + someGroupOrMethodToGetGroup);
    socket.on('message', function(msg){
        displayMessage(msg);
    }
    nsp = '/' + someGroupOrMethodToGetGroup;
}, 1500);

Then in my displayMessage code I have:

socketOut.emit('message', { msg: desiredMessage, nsp: nsp });

From another answer of mine (https://stackoverflow.com/a/24805494/3842050).

Community
  • 1
  • 1
Blubberguy22
  • 1,344
  • 1
  • 17
  • 29