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'});
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!
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.
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.
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'});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With