簡體   English   中英

為什么我的websocket php + javascript代碼無法正常工作?

[英]Why does not working my websocket php+javascript code?

我在互聯網上找到了一些腳本。 我已經嘗試配置它,但是它對我不起作用。 我添加了它,我對websocket函數不太了解,所以請幫助我! 當我嘗試向服務器發送消息時,總是收到相同的錯誤代碼:

“ InvalidStateError:無法在'WebSocket'上執行'send':仍處於CONNECTING狀態。”

該腳本未生成包含此注釋的其他內容:

//與服務器連接的客戶端將進入這種情況

//第一個客戶端將與服務器握手,然后與服務器交換數據

我不知道為什么,但是我真的很想了解這些東西。 能幫我一個人嗎? (握手是可以的。如果還不能,我會收到一個JavaScript錯誤。)

<?php

error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();

$address = "127.0.0.1";
$port = "1234";

GLOBAL $clients;
GLOBAL $client_list;

// socket creation
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);

if (!is_resource($socket))
    console("socket_create() failed: ".socket_strerror(socket_last_error()), true);

if (!socket_bind($socket, $address, $port))
    console("socket_bind() failed: ".socket_strerror(socket_last_error()), true);

if(!socket_listen($socket, 20))
    console("socket_listen() failed: ".socket_strerror(socket_last_error()), true);

console("Server started on $address : $port\n\n");
$master = $socket;
$sockets = array($socket);
$counert = 0;
while(true) {
    $changed = $sockets;
    foreach($changed as $socket) {
        if($socket == $master) {
            $log = "Egyenlők!";
        } else {
            $log = "Nem egyenlők!";
        }
        //console($log);
        if($socket == $master) {
            // new client will enter in this case and connect with server
            socket_select($changed,$write=NULL,$except=NULL,NULL);
            console("Master Socket Changed.\n\n");
            $client = socket_accept($master);
            if($client < 0) {
                console("socket_accept() failed\n\n"); 
                continue; 
            } else {
                console("Connecting socket.\n\n");
                fnConnectacceptedSocket($socket,$client); $master=null;
            }
        } else {
            // clients who are connected with server will enter into this case
            // first client will handshake with server and then exchange data with server

        $client = getClientBySocket($socket);
            if($client) {
                if ($clients[$socket]["handshake"] == false) {
                    $bytes = @socket_recv($client, $data, 2048, MSG_DONTWAIT);
                    if ((int)$bytes == 0)
                        continue;
                        console("Handshaking headers from client:".$data);
                    if (handshake($client, $data, $socket))
                        $clients[$socket]["handshake"] = true;
                    } else if ($clients[$socket]["handshake"] == true) {
                        $bytes = @socket_recv($client, $data, 2048, MSG_DONTWAIT);
                    if ($data != "") {
                        $decoded_data = unmask($data);
                        socket_write($client, encode("You have entered: ".$decoded_data));
                        console("Data from client:".$decoded_data);
                        socket_close($socket);
                    }
                }
            }
        }
    }
}

# Close the master sockets
socket_close($socket);

function unmask($payload) {
    $length = ord($payload[1]) & 127;

    if($length == 126) {
        $masks = substr($payload, 4, 4);
        $data = substr($payload, 8);
    }
    elseif($length == 127) {
        $masks = substr($payload, 10, 4);
        $data = substr($payload, 14);
    }
    else {
        $masks = substr($payload, 2, 4);
        $data = substr($payload, 6);
    }

    $text = '';
for ($i = 0; $i < strlen($data); ++$i) {
        $text .= $data[$i] ^ $masks[$i%4];
    }
    return $text;
}

function encode($text) {
    // 0x1 text frame (FIN + opcode)
    $b1 = 0x80 | (0x1 & 0x0f);
    $length = strlen($text);

    if($length <= 125)      
        $header = pack('CC', $b1, $length);     
    elseif($length > 125 && $length < 65536) 
        $header = pack('CCS', $b1, 126, $length);   
    elseif($length >= 65536)
        $header = pack('CCN', $b1, 127, $length);

    return $header.$text;
}

function fnConnectacceptedSocket($socket, $client) {
    GLOBAL $clients;
    GLOBAL $client_list;
    $clients[$socket]["id"] = uniqid();
    $clients[$socket]["socket"] = $socket;
    $clients[$socket]["handshake"] = false;
    console("Accepted client \n\n");
    $client_list[$socket] = $client;
}

function getClientBySocket($socket) {
    GLOBAL $client_list;
    return $client_list[$socket];
}

function handshake($client, $headers, $socket) {
    if(preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match))
        $version = $match[1];
    else {
        console("The client doesn't support WebSocket");
        return false;
    }

    if($version == 13) {
        // Extract header variables
    if(preg_match("/GET (.*) HTTP/", $headers, $match))
        $root = $match[1];
    if(preg_match("/Host: (.*)\r\n/", $headers, $match))
        $host = $match[1];
    if(preg_match("/Origin: (.*)\r\n/", $headers, $match))
        $origin = $match[1];
    if(preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $headers, $match))
        $key = $match[1];

    $acceptKey = $key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
    $acceptKey = base64_encode(sha1($acceptKey, true));

    $upgrade = "HTTP/1.1 101 Switching Protocols\r\n".
        "Upgrade: websocket\r\n".
        "Connection: Upgrade\r\n".
        "Sec-WebSocket-Accept: $acceptKey".
        "\r\n\r\n";

        socket_write($client, $upgrade);
        return true;
    }
    else {
        console("WebSocket version 13 required (the client supports version {$version})");
        return false;
    }
}

function console($text) {
    $text = $text . "\r\n";
    $File = "log.txt"; 
    $Handle = fopen($File, 'a');
    fwrite($Handle, $text); 
    fclose($Handle);
}

?>

這是javascript代碼:

<script>
var socket;
var host = "ws://localhost:1234/chat/server.php";
function init() {
  try {
    socket = new WebSocket(host);
    //log('WebSocket - status '+socket.readyState);
    socket.onopen    = function(msg){ socket.send("asdf"); log("Welcome - status "+this.readyState); };
    socket.onmessage = function(msg){ log("Received: "+msg.data); };
    socket.onclose   = function(msg){ log("Disconnected - status "+this.readyState); };
  }
  catch(ex){ log(ex); }
  $("msg").focus();
}

function send() {
    var txt,msg;
    txt = $("msg");
    msg = txt.value;
    if(!msg){ alert("Message can not be empty"); return; }
    txt.value="";
    txt.focus();
    try{ socket.send(msg); log('Sent: '+msg); } catch(ex){ log(ex); }
}
function quit(){
    log("Goodbye!");
    socket.close();
    socket=null;
}

// Utilities
function $(id){ return document.getElementById(id); }
function log(msg){ $("log").innerHTML+="\n"+msg; }
function onkey(event){ if(event.keyCode==13){ send(); } }
</script>

您如何精確地運行PHP代碼? 我測試了它,至少在這里發生了什么:)。 我不確定使用PHP實現websocket服務器是否可行!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM