Socket IO Server to Server - javascript

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.

Related

Socket.io - Cant stop passing all data to all clients

I am having a issue where I am pulling data from a DB via node mysql & Express and passing it via socket.io.... but there's an issue am running into.
All users are updating with the same data rather than unique data per user.
For example:
If user A has just logged in he can see all his account details. But when user B logs in right after he can then see all his details....but it then updates user A details to show user B details as well.
I am trying to ensure user A can can only see his own and same for user B.
I have tried numerous things to stop this happening via JQuery but cant seem to find a resolution.
Below I have trimmed down a the code to a basic example:
HTML
<span id="id-val">User A</span>
<span id="user-val"></span>
Server side
server = http.createServer(app),
io = require('socket.io').listen(server);
function SQLuserData(userval) {
connection.getConnection(function (err, connection) {
connection.query('SELECT val FROM test WHERE name= ?;',
[userval],
function (err, rows) {
var accountval = rows[0]['val'];
if (accountval) {
console.log("Val : " + accountval);
UserVal(accountval);
} else {
console.log("Error | Val: " + err);
}
});
connection.release();
});
}
//Socket.io connection socket
io.sockets.on('connection', function (socket) {
socket.on('sqluser', function (userval) {
SQLuserData(userval);
});
});
//Pass val client side.
function UserVal(accountval) {
io.sockets.emit("valsocket", accountval);
}
Client side
var socket = io.connect();
//Used to grab information for that user from serverside.
$(document).ready(function () {
var userval = $('#id-val').text();
socket.emit('sqluser', userval);
});
//Grabs user value being passed from serverside and updates HTML.
socket.on("valsocket", function (accountval) {
$("#user_val").val(accountval);
});
Does anyone have any advice or potential solutions?
you need to grab and store the socket.id for each connected user
var users = {};
//Socket.io connection socket
io.sockets.on('connection', function (socket) {
socket.on('sqluser', function (userval) {
// 'userval' must be unique for each user
users[userval] = socket.id;
SQLuserData(userval);
});
});
and then use the same id to emit data ti single socket
//Pass val client side.
function UserVal(accountval, userval) {
io.sockets.socket(users[userval]).emit("valsocket", accountval);
}
for socket.io version 1.0 and above
io.to(users[userval]).emit("valsocket", accountval);
I think you want to avoid emitting the account data to all connected users, which is what Socket.IO's emit method does. It might be better have the client send a GET request to the server and respond with the account details to the individual client.
Here are some resources if you choose to use an HTTP request over Socket.IO:
jQuery GET
Express Respond
So basically the problem with your code is that you are not distinguishing between users . Since you are sending data through socket you need to be careful to whom you are sending data.
You can use socketio-auth to create a type of authentication . And then send the data as socket.emit(event, data); Where socket is an individual object per user . You can also use a cookie based session to help you with this .

Emit Events To Socket.IO Not Working From Server

i am trying to get a chat program to work using socket.io but it doesnt seem to work properly.
i am using a Node.js server and it seems to be running properly. i think this may have something to do with emitting to rooms.
the code i have on the client browser is:
<script>
var socket = io("https://localhost:3000/userChat");
socket.on('connect', function(){
socket.emit('initialiseConnection', "user1");
});
socket.on('messageIn', function(msg){
console.log(msg);
$('#messages').append($('<li>').text(msg.message));
});
</script>
so when the page loads, socket.io it connects to the server and emits the "initialiseConnection" event on the server with "user1". which is a new room specifically for that user.
on the server, the code i have handling "initialiseConnection" is:
socket.on("initialiseConnection", function(username){
socket.join(username);
console.log(username + " has joined.");
Message.find({recipient:username}, function (err, message){
console.log("messages for "+username+": "+message.length);
for (var x = 0; x < message.length; x++){
console.log(username+"'s message "+x);
console.log(message[x]);
socket.to(username).emit("messageIn", {"message":message[x]});
}
});
});
this code as you can see, creates and joins a room with the same name as the username. the looks in the database for any messages, and tries to emit those messages to the user. i log the message. there is definately a message and the username in the "socket.to()" method is also correctly shown in the logs. but the "socket.on('messageIn')" on the client browser doesnt seem to be picking up the event.
i have also tried putting:
setTimeout(function() {
socket.to(username).emit("messageIn", {"message":"test message"});
}, 5000);
immediately after the socket.join(), in case this was related to some backbround processing that needed to complete
can anyone see where i may have gone wrong on this?
Thanks.
--EDIT 1--------------------------------------
var https = require('https');
var express = require('express');
var app = express();
var server = https.createServer(https_options, app).listen(3000);
var io = require('socket.io')(server);
var userChat = io.of("/userChat");
userChat.on('connection', function(socket){
console.log('a user connected');
socket.on("initialiseConnection", function(username){
...
});
socket.on('disconnect', function(){
socket.leave(socket.room);
});
});
You need to change this:
socket.to(username).emit("messageIn", {"message":message[x]});
to this:
socket.emit("messageIn", {"message":message[x]});
A socket is the endpoint. When sending, you just send directly to the socket. You don't send to a user in a room? You just send to a socket. Since you already have the socket in your socket variable, that's what you send to.

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

nodejs send list of all clients fail

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.

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.

Categories

Resources