0

Web サイトで実行中のチャット アプリケーションがあります。websockets、php を使用して実装されており、正常に動作しています。問題は、1 人のユーザーにメッセージを送信するたびに、現在 Web サイトに接続しているすべてのユーザーにそのメッセージをブロードキャストすることです。誰かが私たちのアプリに接続したときに各ユーザーの一意の ID を取得する方法を誰かが教えてくれれば、本当に役に立ちます。現在ログインしているチャット ユーザーのユーザー ID を取得できれば問題は解決しますが、ユーザーが接続したときにそのユーザー ID を取得できません (websocket のオープン状態)。接続が確立されたときにユーザー ID を取得できますが、接続が行われる前にユーザー ID が必要です。接続が発生すると、接続されたユーザーに独自の ID がシリアルに割り当てられます (1,2,3..,n)。

<?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

<!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>
4

1 に答える 1

2
  1. temp_usersサーバーにアレイを作成します。

  2. 各クライアントが接続したら、一意の ID を作成し、新しいソケットと一意の ID の両方をこの配列に追加してから、ID をクライアントに送信します。ヘッダーには、これがシステム メッセージであることを示します。

  3. クライアント コードで、クライアントにシステム メッセージから一意の ID を取得させます。一意の ID とクライアントのユーザー名を使用してメッセージを作成し、それをサーバーに送り返します。

  4. temp_users受信したユーザー名を配列内の対応する ID にマップします。特定のユーザーを識別し、ユーザー名にマップされたソケットを使用してメッセージを送信できるようになりました。

于 2013-12-16T12:14:56.783 に答える