Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to Socket.IO server with specific path and namespace

My Node.js application is running at URL http://www.example.com/myapp/.

I have configured a Socket.IO server (version 1.3.5) with a custom namespace. Here is an example code snippet:

var server = http.createServer(...); var io = socketio(server); io     .of('/a/b/c')     .on('connection', function (socket) {         socket.emit('update', {msg: '/a/b/c'});     }); 

I can't figure out how to connect to this service from the client. My guesses (none of these is working):

io.connect('http://www.example.com/myapp/a/b/c'); io.connect('http://www.example.com', {path: '/myapp/a/b/c'}); io.connect('', {path: '/myapp/a/b/c'}); io.connect('http://www.example.com/a/b/c', {path: '/myapp'}); io.connect('http://www.example.com', {path: '/myapp/socket.io/a/b/c'}); 
like image 551
guidoman Avatar asked Apr 08 '15 09:04

guidoman


People also ask

How do I connect to a Socket.IO server?

listen(port); // Create a Socket.IO instance, passing it our server var socket = io. listen(server); // Add a connect listener socket. on('connection', function(client){ console. log('Connection to client established'); // Success!

How do I send to a specific socket IO client?

To send a message to the particular client, we are must provide socket.id of that client to the server and at the server side socket.io takes care of delivering that message by using, socket.broadcast.to('ID'). emit( 'send msg', {somedata : somedata_server} ); For example,user3 want to send a message to user1.

Is assigning different endpoints or paths to sockets?

Socket.IO allows you to Namespace your sockets, which essentially means assigning different endpoints or paths. This is a useful feature to minimize the number of resources (TCP connections) and at the same time separate concerns within your application by introducing separation between communication channels.


1 Answers

On your server, don't forget to specify the path as well:

var io  = require('socket.io')(http, { path: '/myapp/socket.io'});  io .of('/my-namespace') .on('connection', function(socket){     console.log('a user connected with id %s', socket.id);      socket.on('my-message', function (data) {         io.of('my-namespace').emit('my-message', data);         // or socket.emit(...)         console.log('broadcasting my-message', data);     }); }); 

On your client, don't confuse namespace and path:

var socket = io('http://www.example.com/my-namespace', { path: '/myapp/socket.io'}); 
like image 161
pieterjandesmedt Avatar answered Oct 17 '22 05:10

pieterjandesmedt