Web套接字无法在我的网站上运行

时间:2017-09-22 07:40:44

标签: php websocket phpwebsocket

我试图了解如何使用我在本网站上找到的这些文件,这样我就可以了解更多关于网络套接字如何与PHP一起使用的信息。所以,我们只是说我有一个网站叫example.com

我需要在这些文件中修改哪些内容才能在我的网站上调用example.com。我一直在寻找如何让这个工作在这里工作,这是该网站的原始解锁代码文件。

的index.php

<html>
<head>
    <style>
    body{width:600px;font-family:calibri;}
    .error {color:#FF0000;}
    .chat-connection-ack{color: #26af26;}
    .chat-message {border-bottom-left-radius: 4px;border-bottom-right-radius: 4px;
    }
    #btnSend {background: #26af26;border: #26af26 1px solid;    border-radius: 4px;color: #FFF;display: block;margin: 15px 0px;padding: 10px 50px;cursor: pointer;
    }
    #chat-box {background: #fff8f8;border: 1px solid #ffdddd;border-radius: 4px;border-bottom-left-radius:0px;border-bottom-right-radius: 0px;min-height: 300px;padding: 10px;overflow: auto;
    }
    .chat-box-html{color: #09F;margin: 10px 0px;font-size:0.8em;}
    .chat-box-message{color: #09F;padding: 5px 10px; background-color: #fff;border: 1px solid #ffdddd;border-radius:4px;display:inline-block;}
    .chat-input{border: 1px solid #ffdddd;border-top: 0px;width: 100%;box-sizing: border-box;padding: 10px 8px;color: #191919;
    }
    </style>    
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>  
    function showMessage(messageHTML) {
        $('#chat-box').append(messageHTML);
    }

    $(document).ready(function(){
        var websocket = new WebSocket("ws://localhost:8090/demo/php-socket.php"); 
        websocket.onopen = function(event) { 
            showMessage("<div class='chat-connection-ack'>Connection is established!</div>");       
        }
        websocket.onmessage = function(event) {
            var Data = JSON.parse(event.data);
            showMessage("<div class='"+Data.message_type+"'>"+Data.message+"</div>");
            $('#chat-message').val('');
        };

        websocket.onerror = function(event){
            showMessage("<div class='error'>Problem due to some Error</div>");
        };
        websocket.onclose = function(event){
            showMessage("<div class='chat-connection-ack'>Connection Closed</div>");
        }; 

        $('#frmChat').on("submit",function(event){
            event.preventDefault();
            $('#chat-user').attr("type","hidden");      
            var messageJSON = {
                chat_user: $('#chat-user').val(),
                chat_message: $('#chat-message').val()
            };
            websocket.send(JSON.stringify(messageJSON));
        });
    });




    </script>
    </head>
    <body>
        <form name="frmChat" id="frmChat">
            <div id="chat-box"></div>
            <input type="text" name="chat-user" id="chat-user" placeholder="Name" class="chat-input" required />
            <input type="text" name="chat-message" id="chat-message" placeholder="Message"  class="chat-input chat-message" required />
            <input type="submit" id="btnSend" name="send-chat-message" value="Send" >
        </form>
</body>
</html>

PHP-socket.php

<?php
define('HOST_NAME',"localhost"); 
define('PORT',"8090");
$null = NULL;

require_once("class.chathandler.php");
$chatHandler = new ChatHandler();

$socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socketResource, 0, PORT);
socket_listen($socketResource);

$clientSocketArray = array($socketResource);
while (true) {
    $newSocketArray = $clientSocketArray;
    socket_select($newSocketArray, $null, $null, 0, 10);

    if (in_array($socketResource, $newSocketArray)) {
        $newSocket = socket_accept($socketResource);
        $clientSocketArray[] = $newSocket;

        $header = socket_read($newSocket, 1024);
        $chatHandler->doHandshake($header, $newSocket, HOST_NAME, PORT);

        socket_getpeername($newSocket, $client_ip_address);
        $connectionACK = $chatHandler->newConnectionACK($client_ip_address);

        $chatHandler->send($connectionACK);

        $newSocketIndex = array_search($socketResource, $newSocketArray);
        unset($newSocketArray[$newSocketIndex]);
    }

    foreach ($newSocketArray as $newSocketArrayResource) {  
        while(socket_recv($newSocketArrayResource, $socketData, 1024, 0) >= 1){
            $socketMessage = $chatHandler->unseal($socketData);
            $messageObj = json_decode($socketMessage);

            $chat_box_message = $chatHandler->createChatBoxMessage($messageObj->chat_user, $messageObj->chat_message);
            $chatHandler->send($chat_box_message);
            break 2;
        }

        $socketData = @socket_read($newSocketArrayResource, 1024, PHP_NORMAL_READ);
        if ($socketData === false) { 
            socket_getpeername($newSocketArrayResource, $client_ip_address);
            $connectionACK = $chatHandler->connectionDisconnectACK($client_ip_address);
            $chatHandler->send($connectionACK);
            $newSocketIndex = array_search($newSocketArrayResource, $clientSocketArray);
            unset($clientSocketArray[$newSocketIndex]);         
        }
    }
}
socket_close($socketResource);

class.chathandler.php

<?php
class ChatHandler {
    function send($message) {
        global $clientSocketArray;
        $messageLength = strlen($message);
        foreach($clientSocketArray as $clientSocket)
        {
            @socket_write($clientSocket,$message,$messageLength);
        }
        return true;
    }

    function unseal($socketData) {
        $length = ord($socketData[1]) & 127;
        if($length == 126) {
            $masks = substr($socketData, 4, 4);
            $data = substr($socketData, 8);
        }
        elseif($length == 127) {
            $masks = substr($socketData, 10, 4);
            $data = substr($socketData, 14);
        }
        else {
            $masks = substr($socketData, 2, 4);
            $data = substr($socketData, 6);
        }
        $socketData = "";
        for ($i = 0; $i < strlen($data); ++$i) {
            $socketData .= $data[$i] ^ $masks[$i%4];
        }
        return $socketData;
    }

    function seal($socketData) {
        $b1 = 0x80 | (0x1 & 0x0f);
        $length = strlen($socketData);

        if($length <= 125)
            $header = pack('CC', $b1, $length);
        elseif($length > 125 && $length < 65536)
            $header = pack('CCn', $b1, 126, $length);
        elseif($length >= 65536)
            $header = pack('CCNN', $b1, 127, $length);
        return $header.$socketData;
    }

    function doHandshake($received_header,$client_socket_resource, $host_name, $port) {
        $headers = array();
        $lines = preg_split("/\r\n/", $received_header);
        foreach($lines as $line)
        {
            $line = chop($line);
            if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
            {
                $headers[$matches[1]] = $matches[2];
            }
        }

        $secKey = $headers['Sec-WebSocket-Key'];
        $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
        $buffer  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
        "Upgrade: websocket\r\n" .
        "Connection: Upgrade\r\n" .
        "WebSocket-Origin: $host_name\r\n" .
        "WebSocket-Location: ws://$host_name:$port/demo/shout.php\r\n".
        "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
        socket_write($client_socket_resource,$buffer,strlen($buffer));
    }

    function newConnectionACK($client_ip_address) {
        $message = 'New client ' . $client_ip_address.' joined';
        $messageArray = array('message'=>$message,'message_type'=>'chat-connection-ack');
        $ACK = $this->seal(json_encode($messageArray));
        return $ACK;
    }

    function connectionDisconnectACK($client_ip_address) {
        $message = 'Client ' . $client_ip_address.' disconnected';
        $messageArray = array('message'=>$message,'message_type'=>'chat-connection-ack');
        $ACK = $this->seal(json_encode($messageArray));
        return $ACK;
    }

    function createChatBoxMessage($chat_user,$chat_box_message) {
        $message = $chat_user . ": <div class='chat-box-message'>" . $chat_box_message . "</div>";
        $messageArray = array('message'=>$message,'message_type'=>'chat-box-html');
        $chatMessage = $this->seal(json_encode($messageArray));
        return $chatMessage;
    }
}
?>

我按照该网站的说明进行操作,但即使我在index.php上修改它所说的ws:// localhost:8090 / demo / php-socket.php,它仍然无法正常工作文件。

0 个答案:

没有答案