Additional options with socket.io

How to send additional parameters using a connection in socket.io? Therefore, when the client connects, they send additional information, and on the server side - how

io.on('connection', function(client, param1, param2, param3) { // app code } 
+6
source share
1 answer

Here is a little trick that should work. First, you create your own Socket client, which sends a message on the first connection (containing all your additional information).

 // Client side io.MySocket = function(your_info, host, options){ io.Socket.apply(this, [host, options]); this.on('connect', function(){ this.send({__special:your_info}); }); }; io.util.inherit(io.MySocket, io.Socket); var my_info = {a:"ping"} var socket = io.MySocket(my_info); 

Then, on the server side, you modify your socket to listen for a special message and fire an event when it does.

 // Server side var io = require('socket.io').listen(app); io.on('connection', function(client){ client.on('message', function(message){ if (message.__special) { io.emit('myconnection', client, message.__special); } }); }); io.on('myconnection', function(client, my_info) { // Do your thing here client.on('message', ...); // etc etc } 

This is the method I used to bind session processing to Socket.IO for the package I wrote.

+13
source

Source: https://habr.com/ru/post/890090/


All Articles