nodejs send list of all clients fail - javascript

js.
Currently I have done several tests successfully
Hello world
server-client communication with events
many rooms
But i can't send the client, to the clients, i use socket.io
The reason I want to do this, is to have a list of current clients
EDIT:
I need to store information for each user in server side
i try use
var io = require('socket.io');
var socket = io.listen(9876);
socket.on('connection', function(client) {
client.join('room');
console.log('new client ' + client.toString());
client.in('room').emit('list', client ); //<-- Error here
client.on('message', function(event) {
console.log('client message! ', event);
client.send(event);
});
client.on('chat', function(data) {
client.broadcast.in('room').emit('LDS', data);
client.in('room').emit('LDS', data);
});
client.on('disconnect', function() {
console.log('out');
});
});
but throws this error
connections property is deprecated. Use getConnections() method
C:\Repos\InWeb\NO\node_modules\socket.io\lib\parser.js:75
data = JSON.stringify(ev);
^
TypeError: Converting circular structure to JSON
at Object.stringify (native)
The original idea is send a list of clients, like this
var listClients;
socket.on('connection', function(client) {
client.join('room');
listClients.push(client);
client.in('room').emit('list', listClients); //<-- But throws same error
I guess that the error is given by the client context
I can fix it?

You send whole object client, you should use something like this
Socket.io Connected User Count
or create array with name and id and send array not whole node object.

Related

Can't send message to only one specific room through node.js and socket.io

I have a problem that i don't seems to be able to solve it. I'm doing some kind of integration with remote system and my code is in iframe but that can't be important for this one i hope :).
I'm trying to send a message from server to specific room/client to begin session. First thing I do is when user log in, I emit message from client side with username.
CLIENT.JS
conn.on('connect', function () {
conn.emit('session', { username: 'some_username' });
}, false);
And on server side i get message and join socket to the room.
SERVER.JS
socket.on('session', function(session) {
socket.join(session.username);
});
I have another module that communicates with this server.js script through redis. So i have two more events in server.js
SERVER.JS
var userCreate = redis.createClient();
userCreate.subscribe("userCreate", "userCreate");
var userDestroy = redis.createClient();
userDestroy.subscribe("userDestroy", "userDestroy");
userCreate.on("message", function(channel, data) {
socket.to(JSON.parse(data).username).emit('beginSession', data);
});
userDestroy.on("message", function(channel, data) {
socket.to(JSON.parse(data).username).emit('endSession', data);
socket.leave(JSON.parse(data).username);
});
But when ever i try to emit message from server to client i broadcast message to everyone. What am I doing wrong?
Well, from the syntax point of view you are doing everything correct.
Didn't you forget to specify the userId property in the endSession?
userDestroy.on("message", function(channel, data) {
socket.to(JSON.parse(data).userId).emit('endSession', data);
socket.leave(JSON.parse(data).userId);
});
If that doesn't work - you should provide the contents of a data object

Why don't I see a response from socket.io-client with node.js?

var io = require('socket.io-client'),
socket = io.connect('targeturl', {
port: 8080
});
socket.on('connect', function () {
console.log("socket connected"); //this is printed.
});
socket.emit('list', {"user":'username',"token": 'mytoken'});
socket.on('message', function(data){
console.log(data);
});
socket.on('error', function(data){
console.log(data); //nothing is printed
});
I see the message 'socket connected' when running this from node.js on the command line but I don't see a response from the 'list' call.
Note that this is a specific question about using socket-io-client from Node.js as a command line application.
I have verified using curl that I can reach the socket server which is REMOTE i.e I do not have the server code but I know that it uses socket.io.
I'm no expert on the matter, but it appears you're attempting to emit the message before the connection is established. (This stuff is asynchronous after all.)
Try moving the emit call inside of the handler for the 'connect' event, to ensure that it happens afterward.

nodejs socket emit return undefined

I am trying to send to clients whenever a new connection issued.
My server side javascripts is :
var clients = 0;
io.sockets.on('connection', function (socket) {
clients ++;
console.log(clients);
socket.broadcast.emit('connect',socket.clients);
}
and my client side js to handle:
socket.on('connect', function (data) {
console.log('on'+data);});
the output is undefined (on undefined)
Where 's things wrong?
socket.broadcast.emit('connect',socket.clients);
^^^^^^^^^^^^^^ this should be 'clients'
Also, connect is a pre-defined event with socket.io, so you shouldn't reuse it or it might give unexpected results.
FWIW: socket.broadcast.emit will send a message to all connections except the current one. If that's not what you want (you want the message to be sent to all connections), use io.sockets.emit instead).

socket.io not working on several clients

I'm trying to build a simple chat client and am having some issues getting it working across multiple clients. Chances are I've missed something really simple. When I send something from one client it is logged in that client but not in any others.
Server:
var io = require('socket.io').listen(5000);
io.sockets.on('connection', function (socket) {
socket.on('send', function (data) {
socket.emit('receive', data);
});
});
Client:
var socket = io.connect('http://localhost:5000');
socket.on('receive', function(data){
console.log("Data received at " + new Date() + ": " + data);
});
The socket variable that gets passed to your callback function is a handle on the client that connected, so socket.emit is behaving correctly, i.e. it should only send to the client that originated it.
Try:
socket.broadcast.emit('receive', data);
to send to everybody except the originating client, or
io.sockets.emit('receive', data);
to send to all clients including the originator.
You want to emit on all sockets, not just the one that sent the message.
So you should be using:
io.sockets.emit('recieve', data);
This is assuming that you aren't logging the data on the sending client before sending it to the server. In that case you'll want to use:
socket.broadcast.emit('recieve', data);
Which will send the message to all connected clients except the sender.
See here for reference on Socket.io
Edit: Trevor beat me to it. However, for some additional clarification: io.sockets is the same as io.of(''). Which is handy to know for when you start using namespaces in a scoket.io app.

Socket IO Server to Server

Is it possible for a server to connect to another using Socket.IO and be treated like a client?
And have it join rooms, recieve io.sockets.in('lobby').emit(). And more?
The first server is also listening for connections/messages as well.
Hey Brad, here's my full .js app below for reference:
var io = require("socket.io").listen(8099);
io.set('log level', 1);
io.sockets.on("connection", function (socket) {
console.log('A Client has Connected to this Server');
//Let Everyone Know I just Joined
socket.broadcast.to('lobby').emit("message",'UC,' + socket.id); // Send to everyone in Room but NOT me
socket.on("message", function (data) {
//Missing code
socket2.send('message,' + data); //Forward Message to Second Server
});
socket.on("disconnect", function (data) {
//Send Notification to Second Server
//Need to figure out later
//Send Notification to Everyone
socket.broadcast.emit("message",'UD,' + socket.id ); //Send to Everyone but NOT me
//Remove user from Session ID
arSessionIDs.removeByValue(socket.id);
//Send Notification to Console
console.log("disconnecting " + arRoster[socket.id][1]);
});
});
var io_client = require( 'socket.io-client' );
var socket2 = io_client.connect('http://192.168.0.104:8090');
socket2.on('connect', function () {
socket2.emit('C3434M,Test');
});
Yes, absolutely. Just use the Socket.IO client in your server application directly.
https://github.com/LearnBoost/socket.io-client
You can install it with npm install socket.io-client. Then to use:
var socket = io.connect('http://example.com');
socket.on('connect', function () {
// socket connected
socket.emit('server custom event', { my: 'data' });
});
I realize this is an old post, but I was working on something similar and decided to come back and contribute something as it got me thinking.
Here's a basic Client -> Server 1 -> Server 2 setup
Server #1
// Server 1
var io = require("socket.io").listen(8099); // This is the Server for SERVER 1
var other_server = require("socket.io-client")('http://example.com:8100'); // This is a client connecting to the SERVER 2
other_server.on("connect",function(){
other_server.on('message',function(data){
// We received a message from Server 2
// We are going to forward/broadcast that message to the "Lobby" room
io.to('lobby').emit('message',data);
});
});
io.sockets.on("connection",function(socket){
// Display a connected message
console.log("User-Client Connected!");
// Lets force this connection into the lobby room.
socket.join('lobby');
// Some roster/user management logic to track them
// This would be upto you to add :)
// When we receive a message...
socket.on("message",function(data){
// We need to just forward this message to our other guy
// We are literally just forwarding the whole data packet
other_server.emit("message",data);
});
socket.on("disconnect",function(data){
// We need to notify Server 2 that the client has disconnected
other_server.emit("message","UD,"+socket.id);
// Other logic you may or may not want
// Your other disconnect code here
});
});
And here's Server #2
// Server 2
var io = require("socket.io").listen(8100);
io.sockets.on("connection",function(socket){
// Display a connected message
console.log("Server-Client Connected!");
// When we receive a message...
socket.on("message",function(data){
// We got a message. I don't know, what we should do with this
});
});
This is our Client, who sends the original message.
// Client
var socket = io('http://localhost');
socket.on('connect', function(){
socket.emit("message","This is my message");
socket.on('message',function(data){
console.log("We got a message: ",data);
});
});
I am making this post a Community Wiki so that someone can improve this if they feel like it.
The code has not been tested, use at your own risk.
I had the same problem, but instead to use socket.io-client I decided to use a more simple approach (at least for me) using redis pub/sub, the result is pretty simple.
You can take a look at my solution here: https://github.com/alissonperez/scalable-socket-io-server
With this solution you can have how much process/servers you want (using auto-scaling solution), you just use redis as a way to forward your messages between your servers.

Categories

Resources