使用Socket.io与多个客户端连接到同一服务器

3

服务器 -

  var dgram = require('dgram');
  var client= dgram.createSocket('udp4');

    /** @requires socket.io */
  var io = require('socket.io')(http);

  /** Array of clients created to keep track of who is listening to what*/
      var clients = [];

      io.sockets.on('connection', function(socket, username){
        /** printing out the client who joined */
        console.log('New client connected (id=' + socket.id + ').');

        /** pushing new client to client array*/
        clients.push(socket);



      /** listening for acknowledgement message */
      client.on('message', function( message, rinfo ){
        /** creating temp array to put data in */
        var temp = [];
        /**converting data bit to bytes */
        var number= req.body.size * 2
        /** acknowledgement message is converted to a string from buffer */
        var message = message.toString();
        /** cutting hex string to correspong to requested data size*/
        var data = message.substring(0, number);
        /** converting that data to decimal */
        var data = parseInt(data, 16);
        /** adding data to data array */
        temp[0] = data
        /** emitting message to html page */
        socket.emit('temp', temp);
      });

      /** listening if client has disconnected */
      socket.on('disconnect', function() {
          clients.splice(clients.indexOf(client), 1);
          console.log('client disconnected (id=' + socket.id + ').');
          clearInterval(loop);
      });
    });
  }
});

客户端-

var socket = io.connect('192.168.0.136:3000');



  socket.on(temp', function(temp){
      var temp= temp.toString();
    var message= temp.split(',').join("<br>");
    $('#output').html('<output>' + message + '</output>');
  });

当客户端连接时,服务器会向客户端发送一个名为temp的随机数。上述代码适用于当一个客户端连接到服务器时。现在你如何让每次都建立一个新的连接?这样如果打开一个标签页,它就会收到自己的随机消息,而当另一个标签页打开时,它也会收到自己的随机消息。


你可以将一个id发送回客户端并保存到localStorage(或变量或其他任何地方)。然后让客户端监听一个专门为该客户端设置的“房间”。例如:`var uuidSocket = io(serverHost + "/" + uuid); uuidSocket.on("Info", (data:any)=> { // do something on data });` 该id/房间将被服务器用于通知特定的客户端。以此类推。 - mkaran
你能否给我一个更好的例子? - TheFlight
1
我已经添加了一个答案,希望能有所帮助! - mkaran
3个回答

3
你可以使用广播消息。 广播指的是向除了发起它的套接字之外的所有人发送消息。 服务器:
var io = require('socket.io')(80);

io.on('connection', function (socket) {
  socket.broadcast.emit('user connected');
});

3
您可以试试这样做: 服务器端:
// you have your socket ready and inside the on('connect'...) you handle a register event where the client passes an id if one exists else you create one.

socket.on('register', function(clientUuid){ // a client requests registration
      var id = clientUuid == null? uuid.v4() : clientUuid; // create an id if client doesn't already have one
      var nsp;
      var ns = "/" + id;

      socket.join(id);
      var nsp = app.io.of(ns); // create a room using this id that is only for this client
      clientToRooms[ns] = nsp; // save it to a dictionary for future use

      // set up what to do on connection
      nsp.on('connection', function(nsSocket){
        console.log('someone connected');

        nsSocket.on('Info', function(data){
          // just an example
        });
      });

客户端:

// you already have declared uuid, uuidSocket and have connected to the socket previously so you define what to do on register:
    socket.on("register", function(data){
      if (uuid == undefined || uuidSocket == undefined) {// first time we get id from server
        //save id to a variable
        uuid = data.uuid;

        // save to localstorage for further usage (optional - only if you want one client per browser e.g.)
        localStorage.setItem('socketUUID', uuid);

        uuidSocket = io(serverHost + "/" + uuid); // set up the room --> will trigger nsp.on('connect',... ) on the server

        uuidSocket.on("Info", function(data){
          //handle on Info
        });

// initiate the register from the client
 socket.emit("register", uuid);

0
从我在代码中看到的情况来看,每个命名空间(命名空间是URI的路径部分)都有一个套接字。因此,您不能为相同的命名空间创建新的套接字,因为它们都将使用相同的套接字。
解决方案是使用带正则表达式的动态命名空间服务器
io.of(/^\/path\/([0-9a-fA-F-]+)$/).on('connection', (socket) => {
    console.log(`${socket.nsp?.name}: new connection with id '${socket.id}'`);
    const namespace = socket.nsp?.name;
    socket.on('event_for_server', ...);
    io.of(namespace).emit('event_for_client', ...);
    socket.disconnect();
});

客户端(Java)

final String uuid = UUID.randomUUID().toString();
final Socket socket = IO.socket("http://.../path/" + uuid, options);
socket.on("connect", args -> {
    socket.emit("event_for_server", ...);
});
socket.on("event_for_client", args -> {
    ...
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接