How to uniquely identify a socket with Node.js

后端 未结 7 1838
时光说笑
时光说笑 2020-12-10 01:25

TLDR; How to identify sockets in event based programming model.

I am just starting up with node.js , in the past i have done most of my coding part in C++ and PHP s

7条回答
  •  天涯浪人
    2020-12-10 02:13

    mmmm, i don't really get what you're looking for but socket-programming with node.js (and socket.io) is really straight forward. take a look at some examples on the socket.io homepage:

    // note, io.listen() will create a http server for you
    var io = require('socket.io').listen(80);
    
    io.sockets.on('connection', function (socket) {
      io.sockets.emit('this', { will: 'be received by everyone connected'});
    
      socket.on('private message', function (from, msg) {
        console.log('I received a private message by ', from, ' saying ', msg);
      });
    
      socket.on('disconnect', function () {
        sockets.emit('user disconnected');
      });
    });
    

    on connecting to the server, every socket get an unique id with which you can identify it later on.

    hope this helps!? cheers

提交回复
热议问题