PHP WebSocket问题

3
我是一名有用的助手,可以为您翻译文本。
我是新手,对于Web套接字还不熟悉。我创建了我的第一个Web套接字,但现在运行时出现问题!
以下是套接字的代码:
// set some variables 
$host = "127.0.0.1"; 
$port = 1234; 

// don't timeout! 
set_time_limit(0); 

// create socket 
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); 
if($socket){
    echo "socket created .... $socket\n";
}

// bind socket to port 
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n"); 
if($result){
    echo "socket binded ... $result\n";
}
// start listening for connections 
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n"); 
if($result){
    echo "socket is now listening ... $result";
}
// accept incoming connections 
// spawn another socket to handle communication 
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); 
if($spawn){
    echo $spawn."\n";
}
// read client input 
$input = socket_read($spawn, 1024) or die("Could not read input\n"); 
if($input){
    echo $input."\n";
}
// clean up input string 
$input = trim($input); 

// reverse client input and send back 
$output = strrev($input) . "\n"; 
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n"); 

// close sockets 
socket_close($spawn); 
socket_close($socket);

现在我该如何运行这段代码?我在我的XAMPP shell上写了以下代码:
php htdocs/socket/server.php -q

它显示:

socket created....Resource id #4
socket binded... 1
socket is now listening...1 Resource is #5
GET socket/server.php HTTP 1.1
upgrade: WebSocket
connection: Upgrade
Host: http://localhost
sec-WebSocket-key1: 14 53    8501 z4 5R'
sec-WebSocket-key2: S 9\ 2s63, *8460!~MO@

现在我该如何运行它?我该如何向它发送输入并如何与JavaScript一起使用?

我写了一个JavaScript代码,但它只连接了一秒钟就断开了...

以下是JavaScript代码:

$(document).ready(function() {

if(!("WebSocket" in window)){
    $('#chatLog, input, button, #examples').fadeOut("fast");    
    $('<p>Oh no, you need a browser that supports WebSockets. How about <a   href="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');       
}else{
    //The user has WebSockets

connect();

function connect(){
        var socket;
        var host = "ws://localhost:1234/websocket_source_files/myown.php";

        try{
            var socket = new WebSocket(host);
            message('<p class="event">Socket Status: '+socket.readyState);
            socket.onopen = function(){
                message('<p class="event">Socket Status: '+socket.readyState+' (open)');    
            }

            socket.onmessage = function(msg){
                message('<p class="message">Received: '+msg.data);                  
            }

            socket.onclose = function(){
                message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
            }           

        } catch(exception){
            message('<p>Error'+exception);
        }

        function send(){
            var text = $('#text').val();
            if(text==""){
                message('<p class="warning">Please enter a message');
                return ;    
            }
            try{
                socket.send(text);
                message('<p class="event">Sent: '+text)
            } catch(exception){
                message('<p class="warning">');
            }
            $('#text').val("");
        }

        function message(msg){
            $('#chatLog').append(msg+'</p>');
        }//End message()

        $('#text').keypress(function(event) {
                  if (event.keyCode == '13') {
                     send();
                   }
        }); 

        $('#disconnect').click(function(){
            socket.close();
        });

    }


}//End connect()

});
</script>

<title>WebSockets Client</title>

</head>
<body>
<div id="wrapper">

<div id="container">

    <h1>WebSockets Client</h1>

    <div id="chatLog">

    </div>
    <p id="examples">e.g. try 'hi', 'name', 'age', 'today'</p>

    <input id="text" type="text" />
    <button id="disconnect">Disconnect</button>

</div>

  </div>
</body>
</html>​

请帮我运行这段代码并学习WebSockets技术。我真的需要在我的学校项目中使用它们。


请使用编辑器工具对您的帖子进行适当的格式化,以便我们能够真正阅读它... - Lukas Knuth
3个回答

2
socket_accept函数将会阻塞(等待),直到有客户端连接。这是它的标准行为。
但是,在连接套接字后执行的函数不会阻塞(除非你告诉它们要阻塞)。因此,您需要告诉脚本等待直到可以从套接字读取数据。
为此,使用socket_set_block函数。另外,您可能还想使用socket_last_error函数检查任何可能的错误。
尽管如此,我认为Java或C更适合使用套接字。

0

你没有正确地进行握手。

从你发布的内容来看,你正在处理ietf-00实现(https://datatracker.ietf.org/doc/html/draft-ietf-hybi-thewebsocketprotocol-00

这是旧版本且已弃用,最新版本似乎是ietf-10(https://datatracker.ietf.org/doc/html/draft-ietf-hybi-thewebsocketprotocol-10)。

你需要的握手基本描述可以在这里找到:http://en.wikipedia.org/wiki/WebSockets

(你可以在其中找到链接到更新和官方规范的链接)。

在你的情况中,重要的部分是:

Sec-WebSocket-Key1和Sec-WebSocket-Key2字段以及字段后的8个字节是服务器用来构建握手结束时的16字节令牌的随机令牌,以证明它已经读取了客户端的握手。握手是通过将第一个密钥中的数字连接起来并除以空格数来构建的。然后为第二个密钥重复此过程。两个结果数字与字段后的最后8个字节连接在一起。最终结果是连接字符串的MD5总和。握手看起来像HTTP,但实际上不是。它允许服务器将握手请求的一部分解释为HTTP,然后切换到WebSocket。一旦建立,WebSocket数据帧可以在全双工模式下在客户端和服务器之间来回发送。文本帧可以全双工发送,可以同时在任何方向上发送。数据最小化框架只有两个字节。每个帧以0x00字节开头,以0xFF字节结尾,并在中间包含UTF-8数据。API尚不支持二进制帧。WebSocket文本帧使用终止符,而二进制帧使用长度前缀。

现在,这里有一些代码(它将接受一个连接,接收一条消息,然后发送一个响应,就像一个非常基本和原始的示例,展示如何完成):

// Just to log to console
function myLog($msg)
{
    echo date('m/d/Y H:i:s ', time()) . $msg . "\n";
}

// This will actually read and process the key-1 and key-2 variables, doing the math for them
function getWebSocketKeyHash($key)
{
    $digits = '';
    $spaces = 0;
    // Get digits
    preg_match_all('/([0-9])/', $key, $digits);
    $digits = implode('', $digits[0]);
    // Count spaces
    $spaces = preg_match_all("/\\s/ ", $key, $dummySpaces);
    $div = (int)$digits / (int)$spaces;
    myLog('key |' . $key . '|: ' . $digits . ' / ' . $spaces . ' = ' . $div);
    return (int)$div;
}

// This will read one header: value from the request header
function getWebSocketHeader($buffer, &$lines, &$keys)
{
    preg_match_all("/([a-zA-Z0-9\\-]*)(\\s)*:(\\s)*(.*)?\r\n/", $buffer, $headers);
    $lines = explode("\r\n", $buffer);
    $keys = array_combine($headers[1], $headers[4]);
 }

// This is where the handshake gets done
function handshake($peer)
{
    $buffer = socket_read($peer, 4096, PHP_BINARY_READ);
    socket_getpeername($peer, $address, $port);
    $peerName = $address . ':' . $port;
    myLog('Got from: ' . $peerName . ': ' . $buffer);
    getWebSocketHeader($buffer, $lines, $keys);
    if (!isset($keys['Sec-WebSocket-Key1']) || !isset($keys['Sec-WebSocket-Key2'])) {
        myLog('Invalid websocket handshake for: ' . $peerName);
        return;
    }
    $key1 = getWebSocketKeyHash($keys['Sec-WebSocket-Key1']);
    $key2 = getWebSocketKeyHash($keys['Sec-WebSocket-Key2']);
    $code = array_pop($lines);
    // Process the result from both keys and form the response header
    $key = pack('N', $key1) . pack('N', $key2) . $code;
    myLog('1:|' . $key1 . '|- 2:|' . $key2 . '|3:|' . $code . '|4: ' . $key);
    $response = "HTTP/1.1 101 WebSocket Protocol Handshake\r\n";
    $response .= "Upgrade: WebSocket\r\n";
    $response .= "Connection: Upgrade\r\n";
    $response .= "Sec-WebSocket-Origin: " . trim($keys['Origin']) . "\r\n";
    $response .= "Sec-WebSocket-Location: ws://" . trim($keys['Host']) . "/\r\n";
    $response .= "\r\n" . md5($key, true); // this is the actual response including the hash of the result of processing both keys
    myLog($response);
    socket_write($peer, $response);
}

// This is where you can send a frame (delimited by 0x00 and 0xFF)
function send($peer, $message)
{
    socket_write($peer, pack('c', (int)0) . utf8_encode($message) . pack('c', (int)255));
}

// This is where you receive a frame (delimited again by 0x00 and 0xFF)
function receive($peer)
{
    $buffer = socket_read($peer, 4096, PHP_BINARY_READ);
    if (empty($buffer)) {
        myLog('Error receiving from peer');
        return;
    }
    return substr($buffer, 1, -1);
}

// Now create a socket
$socket = socket_create_listen(1026);
$peer = socket_accept($socket);

// Do the handshake and wait for an incoming message from the client
handshake($peer);
myLog('Got ' . receive($peer));

// Respond!
send($peer, 'hi there');
socket_close($peer);
socket_close($socket);

编辑:

这是一个非常基本的HTML,在Chrome中可以正常工作(至少在我的电脑上):

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
  if ("WebSocket" in window)
  {
     // Let us open a web socket
     var ws = new WebSocket("ws://host:1026");
     ws.onopen = function()
     {
        // Web Socket is connected, send data using send()
        ws.send("Message to send");
        console.log('send');
     };
     ws.onmessage = function (evt)
     {
        var received_msg = evt.data;
        console.log(received_msg);
        var txt = document.createTextNode(received_msg);
        document.getElementById('messages').appendChild(txt);
     };
     ws.onclose = function()
     {
        // websocket is closed.
        console.log('close');
     };
  }
  else
  {
     // The browser doesn't support WebSocket
     alert("WebSocket NOT supported by your Browser!");
  }
}
</script>
</head>
<body>
<div id="sse">
   <a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
<div id="messages">
</div>
</body>
</html>

0
编写另一个 PHP 脚本,用于连接它。

检查JavaScript代码,它实际上连接到了套接字服务器,但我无法理解和解决的是为什么它会断开连接?以及为什么在Shell屏幕上没有显示任何内容? - Awah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接