简体   繁体   English

Websockets群聊到特定用户

[英]Websockets Group Chat to Specific Users

I have a running chat application in my website. 我的网站上有一个正在运行的聊天应用程序。 It is implemented using websockets, php and is working fine. 它使用websockets,php实现,并且运行良好。 The problem is whenever i send a message to single user it broadcasts that message to all users currently connected to my website. 问题是,每当我向单个用户发送一条消息时,它就会将该消息广播到当前连接到我的网站的所有用户。 It will be really helpful if someone can tell me how to get the unique id of each user when someone connects to our app. 如果有人告诉我如何在连接到我们的应用程序时获取每个用户的唯一ID,这将非常有帮助。 If i can get the userid of the current logged in chat user that would solve my problem but i am unable to retrieve that userid when the user connects (open state of websocket). 如果我可以获取当前登录的聊天用户的用户ID,这可以解决我的问题,但是当用户连接时(Websocket的打开状态),我无法检索该用户ID。 I can get the userid when the connection is made but I need the userid before the connection happens. 建立连接后可以获取用户ID,但是在连接发生之前需要用户ID。 When the connecation occurs it assigns its own ids to the connected users in a serial manner(1,2,3..,n). 当连接发生时,它将以串行方式(1,2,3 ..,n)向连接的用户分配自己的ID。

<?php
// prevent the server from timing out
set_time_limit(0);

// include the web sockets server script (the server is started at the far bottom of this file)
require 'class.PHPWebSocket.php';

// when a client sends data to the server
function wsOnMessage($clientID, $message, $messageLength, $binary) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );

// check if message length is 0
if ($messageLength == 0) {
    $Server->wsClose($clientID);
    return;
}

//Send the message to everyone but the person who said it
foreach ( $Server->wsClients as $id => $client )
    if ( $id != $clientID )
        $Server->wsSend($id, "Visitor $clientID ($ip) said "$message"");
}

// when a client connects
function wsOnOpen($clientID)
{
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );

$Server->log( "$ip ($clientID) has connected." );

//Send a join notice to everyone but the person who joined
foreach ( $Server->wsClients as $id => $client )
    if ( $id != $clientID )
        $Server->wsSend($id, "Visitor $clientID ($ip) has joined the room.");
}

// when a client closes or lost connection
function wsOnClose($clientID, $status) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );

$Server->log( "$ip ($clientID) has disconnected." );

//Send a user left notice to everyone in the room
foreach ( $Server->wsClients as $id => $client )
    $Server->wsSend($id, "Visitor $clientID ($ip) has left the room.");
}

// start the server
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
// for other computers to connect, you will probably need to change this to your LAN IP or external IP,
// alternatively use: gethostbyaddr(gethostbyname($_SERVER['SERVER_NAME']))
$Server->wsStartServer('127.0.0.1', 9300);

?>

HTML HTML

<!doctype html>
<html>
<head>
<meta charset='UTF-8' />
<style>
    input, textarea {border:1px solid #CCC;margin:0px;padding:0px}

    #body {max-width:800px;margin:auto}
    #log {width:100%;height:400px}
    #message {width:100%;line-height:20px}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="fancywebsocket.js"></script>
<script>
    var Server;

    function log( text ) {
        $log = $('#log');
        //Add text to log
        $log.append(($log.val()?"n":'')+text);
        //Autoscroll
        $log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;
    }

    function send( text ) {
        Server.send( 'message', text );
    }

    $(document).ready(function() {
        log('Connecting...');
        Server = new FancyWebSocket('ws://127.0.0.1:9300');

        $('#message').keypress(function(e) {
            if ( e.keyCode == 13 && this.value ) {
                log( 'You: ' + this.value );
                send( this.value );
                $(this).val('');
            }
        });

        //Let the user know we're connected
        Server.bind('open', function() {
            log( "Connected." );
        });

        //OH NOES! Disconnection occurred.
        Server.bind('close', function( data ) {
            log( "Disconnected." );
        });

        //Log any messages sent from server
        Server.bind('message', function( payload ) {
            log( payload );
        });

        Server.connect();
    });
</script>
</head>

<body>
<div id='body'>
    <textarea id='log' name='log' readonly='readonly'></textarea><br/>
    <input type='text' id='message' name='message' />
</div>
</body>

</html>
  1. Create a temp_users array in the server. 在服务器中创建一个temp_users数组。

  2. When each client connects, create a unique ID and add both the new socket and the unique ID to this array, then send the ID to the client, with a header indicating that this is a system message. 当每个客户端连接时,创建一个唯一的ID,并将新的套接字和唯一的ID添加到此阵列,然后将ID发送给客户端,并带有一个标头,表明这是系统消息。

  3. In the client code, have the client retrieve the unique ID from the system message. 在客户端代码中,让客户端从系统消息中检索唯一ID。 Compose a message with the unique ID and the client's username, then send it back to server. 用唯一的ID和客户端的用户名编写一条消息,然后将其发送回服务器。

  4. Map the received username to corresponding ID in temp_users array. 将收到的用户名映射到temp_users数组中的相应ID。 You can now identify a specific user and send them a message using the socket mapped to their username. 现在,您可以标识特定用户,并使用映射到其用户名的套接字向他们发送消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM