Sending message to a specific connected users using webSocket?

后端 未结 5 2134
Happy的楠姐
Happy的楠姐 2020-11-29 15:43

I wrote a code for broadcasting a message to all users:

// websocket and http servers
var webSocketServer = require(\'websocket\').server;

...
...
v         


        
5条回答
  •  粉色の甜心
    2020-11-29 16:11

    I would like to share what I have done. Hope it doesn't waste your time.

    I created database table holding field ID, IP, username, logintime and logouttime. When a user logs in logintime will be currect unixtimestamp unix. And when connection is started in websocket database checks for largest logintime. It will be come user logged in.

    And for when user logs out it will store currect logouttime. The user will become who left the app.

    Whenever there is new message, Websocket ID and IP are compared and related username will be displayed. Following are sample code...

    // when a client connects
    function wsOnOpen($clientID) {
          global $Server;
          $ip = long2ip( $Server->wsClients[$clientID][6] );
    
          require_once('config.php');
          require_once CLASSES . 'class.db.php';
          require_once CLASSES . 'class.log.php';
    
          $db = new database();
          $loga = new log($db);
    
          //Getting the last login person time and username
          $conditions = "WHERE which = 'login' ORDER BY id DESC LIMIT 0, 1";
          $logs = $loga->get_logs($conditions);
          foreach($logs as $rows) {
    
                  $destination = $rows["user"];
                  $idh = md5("$rows[user]".md5($rows["time"]));
    
                  if ( $clientID > $rows["what"]) {
                          $conditions = "ip = '$ip', clientID = '$clientID'  
    
                          WHERE logintime = '$rows[time]'";
                          $loga->update_log($conditions);
                 }
          }
          ...//rest of the things
    } 
    

提交回复
热议问题