PHP流websockets

时间:2015-01-30 21:01:44

标签: javascript php websocket

我有点新的套接字的东西,我试图在PHP上使用我的javascript支持websockets调用,目前我的代码看起来像这样

<?php

class Websocket
{
    private $server;

    private $sockets = [];

    public function create($host)
    {
        $this->server = stream_socket_server('tcp://localhost:8080', $errno, $errmsg);
        stream_set_blocking($this->server, 0);
    }

    public function run()
    {
        while(true)
        {
            $client = stream_socket_accept($this->server);

            if($client)
            {
                $data = stream_socket_recvfrom($client, 2048);

                if($data)
                {
                    echo 'Client connected'.PHP_EOL;
                                        echo $data;
                    $response = $this->handshake($data);

                    stream_socket_sendto($client, $response);
                }
            }
        }
    }

    private function handshake($data)
    {
        $data = explode(PHP_EOL, $data);

        foreach($data as $header)
        {
            $current_header = explode(':', $header);

            if($current_header[0] == 'Sec-WebSocket-Key')
            {
                $accept = base64_encode(sha1(trim($current_header[1]).'258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
                $response = 'HTTP/1.1 101 Switching Protocols'.PHP_EOL.'Upgrade: websocket'.PHP_EOL.'Connection: Upgrade'.PHP_EOL.'Sec-WebSocket-Accept:'.$accept.PHP_EOL.PHP_EOL;

                return $response;
            }
        }
    }
}

我的javascript只是一个简单的

var socket = new WebSocket('ws://localhost:8080');

socket.onopen = function(event) 
{
    console.log('connected');
    socket.send('hello');
}

目前连接的消息显示在我的chrome控制台上,但在此之后应该发送hello消息时出现此错误

“连接到:xxx在页面加载时被中断”

所以我的问题是在我成功向客户端发送握手后如何处理消息?我知道我的代码总是将握手发送到新的连接但是在我的服务器上我只会看到第一条消息回应(http请求)而不是“你好”一个

1 个答案:

答案 0 :(得分:0)

您需要处理消息 -

socket.onmessage = function(e){
   var server_message = e.data;
   console.log(server_message);
}