socket.io - passing events between nodes - socket.io

I was inspired by this: http://socket.io/docs/using-multiple-nodes/#passing-events-between-nodes, and right now I want to synchronize my two socket.io instances through the redis adpter.
This is my code:
//FIRST SERVER (server1.js)
var io = require('socket.io')(3000);
var redis = require('socket.io-redis');
io.adapter(redis({ host: 'localhost', port: 6379 }));
var test = 0;
io.on('connection', function (socket) {
test+=1;
console.log("connection. test = " + test);
});
//SECOND SERVER (server2.js)
var io = require('socket.io')(4000);
var redis = require('socket.io-redis');
io.adapter(redis({ host: 'localhost', port: 6379 }));
var test = 0;
io.on('connection', function (socket) {
test+=1;
console.log("connection. test = " + test);
});
When I connecting to server1.js (port 3000) - I see 'connection. test = 1', it's good, but the console of the second server is still clean. I want second server (port 4000) to do the same (print 'connection = 1').
What I'm doing wrong? Can you show me an example how to use the adapter?
Thanks

If you only connect to server1:3000 there's no way the io.on('connection', ...) would be triggered on server2:4000 - after all, you are not connected to that server.
Each client will connect to only one of your servers. If you were not using the Redis adapter clients connected to different servers would be unable to communicate. Now with the Redis adapter the servers know about the clients of each other and can broadcast messages to all connected clients of all servers.

Related

Sending data received from one socket.io server to a web socket client

I'm starting to use socket.io and I have a problem that I can't solve so far
I have two nodejs running, one is the socket.io data server and the other one is going to interact with web clients
I need to get data from the server and send it to my web clients, the problem is I can't emit data to the clients outside the 'on connect'
I think is better to explain it with a simple example
const socket = require('socket.io-client')('http://localhost:12000');
const SocketIO = require('socket.io');
const app = require('../app');
const server = http.createServer(app);
server.listen(port);
// client socket, this is a regular message from
// the server running on port 12000, it works
socket.on('msg_from_server', data => {
console.log(data);
});
// server socket
const io = SocketIO(server);
io.on('connection', (s) => {
// this works
s.emit('msg_to_client', {data: 'xxxx'})
// this doesn't works
socket.on('msg_from_server', data => {
console.log(data);
});
});
socket client for server on port 12000 and socket from io.on('connection', (socket) both are different. But you are mixing them both.Do something like this:
const Socket_12000 = require('socket.io-client')('http://localhost:12000');
const SocketIO = require('socket.io');
const app = require('../app');
const server = http.createServer(app);
server.listen(port);
// client socket
socket.on('msg_from_server', data => {
console.log(data);
});
// server socket
const io = SocketIO(server);
io.on('connection', (socket) => {
// this works
socket.emit('msg_to_client', {data: 'xxxx'})
// this doesn't works
Socket_12000.on('msg_from_server', data => {
console.log(data);
});
});
I have created a basic gist depicting the problem/solution please commant if you are looking something else.
https://gist.github.com/sandeepp2016/bb1946bcbeb2f11d57bc3aa2e44c158e

Cannot hit simple node web server hosted on EC2 instance

Not able to hit my simple node web server hosted on an ubuntu EC2 in AWS. But I can't see I've missed anything! I've provided screen shots below within AWS - What am I missing? Please help!.
Many thanks,
Node code
const http = require('http');
const hostname = '127.0.0.1';
const port = 8080;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Command prompt
$ node index.js
Command prompt response
Server running at http://127.0.0.1:8080/
EC2 instance
Security settings
Elastic IP settings
Browser
http://"Public DNS (IPv4) value":8080/
Update
When you select the type, select "Custom TCP Rule":
and enter 8080 in the port range field.
EDIT
However, that only gets you part of the way. If you notice, your server is listening on the IP address 127.0.0.1. That means that it's not listen to the outside world, only localhost. To access it outside of the server machine you'll need to change your code to:
const http = require('http');
const hostname = '0.0.0.0';
const port = 8080;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
The change is that you're now listening on "all interfaces" as compared to just localhost.

socket.io connection event never fire

server
var io = require('socket.io'),
UUID = require('node-uuid'),
gameport = 3000;
var db = {
waiting_clients: []
};
var logic = {
};
var sio = io.listen(gameport);
sio.sockets.on('connection', function(socket){
var client = {
id: UUID()
};
socket.emit('news', client);
console.log(client.id);
db.waiting_clients.push(client);
});
test client:
var net = require('net');
var client = net.connect({port: 3000},
function(e) { //'connect' listener
console.log('client connected');
client.end();
});
in test client console, it show "client connected". But there are no output in server console
You must use a socket.io client to connect to a socket.io server. Your code shows that you are trying to make a generic TCP connection to a socket.io server. That will not work. The lowest level connection will be established, but then the initial protocol handshake will fail and the socket.io server will drop the connection and you will never get the connection event.
Socket.io has its own connection scheme built on top of webSocket which is built on top of HTTP which is built on top of TCP.
So, to connect to a socket.io server, you must use a socket.io client that runs both the socket.io and webSocket protocol, not a plain TCP socket.

Connecting socket.io client to https

I'm trying to build a web chat application and want to connect my client to the socket.io server with https.
Seems like everything's fine, but the client is not connecting after all..
Server Code:
var app = require('express')();
var fs = require('fs');
var options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};
var server = require('https').createServer(options, app).listen(3000,function(){
console.log("Https server started on port 3000");
});
var io = require('socket.io').listen(server);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("Client connected");
/*....*/
});
Client code to connect to server:
$(function($){
var socket = io.connect('https://localhost:3000', {secure: true});
.....
});
It kind of doesn't run the code inside of $(function($)..
When I make it a http server it works just fine..
Simply
var socket = io.connect('/', {secure: true});
EDIT: By default socket.io will try to establish a connection on the same host as webserver hosts web content, so no need to specifying host/protocol/port. The / states to connect to default namespace.
I solved the problem..
So for http it was enough if you begin your script on the client with
$(function(){
....
});
But it wouldn't work with https.
I changed it to
jQuery(function($){
....
})(jQuery);
Pretty odd but it worked for me.

Socket.io connection url?

I have the current setup:
Nodejs Proxy (running http-reverse-proxy) running on port 80.
Rails server running on port 3000
Nodejs web server running on port 8888
So any request starting with /nodejs/ will be redirected to nodejs web server on 8888.
Anything else will be redirected to the rails server on port 3000.
Currently Socket.io requires a connection url for io.connect.
Note that /nodejs/socket.io/socket.io.js is valid and returns the required socket.io client js library.
However, I am not able to specify connection_url to /nodejs/ on my server.
I have tried http://myapp.com/nodejs and other variants but I am still getting a 404 error with the following url http://myapp/socket.io/1/?t=1331851089106
Is it possible to tell io.connect to prefix each connection url with /nodejs/ ?
As of Socket.io version 1, resource has been replaced by path. Use :
var socket = io('http://localhost', {path: '/nodejs/socket.io'});
See: http://blog.seafuj.com/migrating-to-socketio-1-0
you can specify resource like this:
var socket = io.connect('http://localhost', {resource: 'nodejs'});
by default resource = "socket.io"
If you are using express with nodejs:
Server side:
var io = require('socket.io')(server, {path: '/octagon/socket.io'});
then
io.on('connection', function(socket) {
console.log('a user connected, id ' + socket.id);
socket.on('disconnect', function() {
console.log('a user disconnected, id ' + socket.id);
})
})
socket.on('publish message ' + clientId, function(msg) {
console.log('got message')
})
Client side:
var socket = io('https://dev.octagon.com:8443', {path: '/octagon/socket.io'})
then
socket.emit('publish message ' + clientId, msg)
I use below approach to achieve this goal:
client side:
var socket = io.connect('http://localhost:8183/?clientId='+clientId,{"force new connection":true});
server side:
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
console.log("url"+socket.handshake.url);
clientId=socket.handshake.query.clientId;
console.log("connected clientId:"+clientId);
});
reference:https://github.com/LearnBoost/socket.io/wiki/Authorizing#global-authorization
If you are serving your app with express, then maybe you can check this out. Remember express uses http to serve your application.
const express = require('express'),
http = require('http'),
socketIo = require('socket.io'),
app = express()
var server = http.createServer(app);
var io = socketIo(server);
io.on('connection', (socket)=>{
// run your code here
})
server.listen(process.env.PORT, ()=> {
console.log('chat-app inintated succesfully')
})

Resources