dongzhan8001 2012-09-26 12:46 采纳率: 0%
浏览 1250

Websocket客户端身份验证问题

如何在基于GoogleWebSocket的聊天系统中对客户端进行身份验证,以便只有有效用户才能发送消息?我希望当客户端请求只在验证连接之后才进行连接。

服务器端代码:

  <?php
// prevent the server from timing out
set_time_limit(0);
include("database.php");

// 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 or trim($message)=='') {
        $Server->wsClose($clientID);
        return;
    }
    // check if either it is valid msg or not
    if (!(substr($message,0,5)=='12345')) {
        $Server->wsSend($clientID, "You are not a valid user so you can not send message.");
        $Server->wsClose($clientID);
        return;
    }


    //The speaker is the only person in the room. Don't let them feel lonely.
    if ( sizeof($Server->wsClients) == 1 )
    {  
        mysql_query( "INSERT INTO message VALUES ( null,1000000000,2000000000,'$message',null )") or die(mysql_error()); 
        $Server->wsSend($clientID, "You  are  alone in chat room");
    }
    else
        //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\"");
        {

        mysql_query( "INSERT INTO message VALUES ( null,1000000000,2000000000,'$message',null )") or die(mysql_error()); 
        $Server->wsSend($id, " ($ip)  \"$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);

?>

客户端代码:

 <!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()?"
":'')+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 );

                    log(  $('#name').val()+" ---> " + this.value );

                    send( $('#key').val()+ $('#name').val()+" ---> " + 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>
        <table width="100%" border="0">
          <tr>
          <td align="center"><label for="name">Enter Your Name:</label><input type="text" name="name" id='name' ><label for="name">Enter Your Key:</label><input type="text" name="key" id='key' ></td>
          </tr>
        </table>
        <br/>
        <label for="message">Enter Your Message:</label><input type='text' id='message' name='message' />
    </div>
</body>

</html>
  • 写回答

1条回答 默认 最新

  • drj26159 2013-04-17 09:20
    关注

    As far as I know you can use standard HTTP authentication mechanism with WebSocket.

    P.S.

    look the similar question

    评论

报告相同问题?

悬赏问题

  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染