将Socket.io与多个客户端连接到同一台服务器 [英] Using Socket.io with multiple clients connecting to same server

查看:949
本文介绍了将Socket.io与多个客户端连接到同一台服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

服务器 -

  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的随机数。上面的代码在一个客户端连接到服务器时起作用。现在,你怎么能每次设置一个新的连接?因此,如果打开一个选项卡,它将获得自己的随机消息,而当另一个选项卡打开时,它将获得自己的随机消息。

When a client connects, a random number called temp is emitted to the client. The above code works when one client connects to the server. Now how can you set a new connection each time? So that if one tab is opened, it gets its own random message back, while when another tab opens, it gets its own random message back.

推荐答案

您可以尝试如下所示:
服务器端:

You could try something like this: Server side:

// 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
        });
      });

客户端:

Client side:

// 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);

这篇关于将Socket.io与多个客户端连接到同一台服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆