簡體   English   中英

將字節數組轉換為可讀字符串

[英]Converting byte array into readable string

我最近一直在嘗試使用websockets作為一種為網站創建簡單登錄系統的方法,但是我遇到了一個大問題。 每當我從網絡套接字發送一條消息時,它就會顯示為一組隨機的數字和字母(大多數顯示為?? s ?? f或類似的名稱)。

static TcpListener server = new TcpListener(IPAddress.Any, 8080);
public static void Main()
{

    server.Start();
   serverstart();
}

public static void serverstart()
{
    TcpClient client = server.AcceptTcpClient();

    Console.WriteLine("A client connected.");

    NetworkStream stream = client.GetStream();

    //enter to an infinite cycle to be able to handle every change in stream

     while (true)
     {
        while (!stream.DataAvailable) ;

        Byte[] bytes = new Byte[client.Available];

        stream.Read(bytes, 0, bytes.Length);

        String data = Encoding.UTF8.GetString(bytes);

        if (new Regex("^GET").IsMatch(data))
        {
            Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
    + "Connection: Upgrade" + Environment.NewLine
    + "Upgrade: websocket" + Environment.NewLine
    + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
        SHA1.Create().ComputeHash(
            Encoding.UTF8.GetBytes(
                new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
            )
        )
    ) + Environment.NewLine
    + Environment.NewLine);
            Console.WriteLine(data);
            stream.Write(response, 0, response.Length);
        }
        else
        {


            Console.WriteLine(data);
            }            


        }
    }
}

WebSockets使用二進制幀來傳輸數據。 為了讀取數據,您必須首先解析幀頭以確定傳輸了多少數據,是否屏蔽了數據等。對數據進行排序后,便知道流中的哪些字節要解碼。 。 有一個很好的參考這里

基本上,它比您想象的要復雜。 與其編寫自己的WebSocketServer,不如考慮使用一些已建立的項目:

暫無
暫無

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

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