How can I send and receive WebSocket messages on the server side?

后端 未结 11 1900
轻奢々
轻奢々 2020-11-22 06:21
  • How can I send and receive messages on the server side using WebSocket, as per the protocol?

  • Why do I get seemingly random bytes at the server when

11条回答
  •  礼貌的吻别
    2020-11-22 06:30

    PHP Implementation:

    function encode($message)
    {
        $length = strlen($message);
    
        $bytesHeader = [];
        $bytesHeader[0] = 129; // 0x1 text frame (FIN + opcode)
    
        if ($length <= 125) {
                $bytesHeader[1] = $length;
        } else if ($length >= 126 && $length <= 65535) {
                $bytesHeader[1] = 126;
                $bytesHeader[2] = ( $length >> 8 ) & 255;
                $bytesHeader[3] = ( $length      ) & 255;
        } else {
                $bytesHeader[1] = 127;
                $bytesHeader[2] = ( $length >> 56 ) & 255;
                $bytesHeader[3] = ( $length >> 48 ) & 255;
                $bytesHeader[4] = ( $length >> 40 ) & 255;
                $bytesHeader[5] = ( $length >> 32 ) & 255;
                $bytesHeader[6] = ( $length >> 24 ) & 255;
                $bytesHeader[7] = ( $length >> 16 ) & 255;
                $bytesHeader[8] = ( $length >>  8 ) & 255;
                $bytesHeader[9] = ( $length       ) & 255;
        }
    
        $str = implode(array_map("chr", $bytesHeader)) . $message;
    
        return $str;
    }
    

提交回复
热议问题