简体   繁体   English

将字节数组转换为可读字符串

[英]Converting byte array into readable string

I have recently been trying out websockets as a way to make a simple login system for a website but i have ran into a big problem. 我最近一直在尝试使用websockets作为一种为网站创建简单登录系统的方法,但是我遇到了一个大问题。 whenever I send a message from the websocket, it shows up as a random set of numbers and letters (mostly comes up as ??s??f or something like that). 每当我从网络套接字发送一条消息时,它就会显示为一组随机的数字和字母(大多数显示为?? 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 use binary frames to transfer data. WebSockets使用二进制帧来传输数据。 In order to read the data you must first parse the Frame Headers to determine how much data was transmitted, whether or not it's masked, etc. One you have that sorted, then you know which bytes in the stream are the ones you want to decode. 为了读取数据,您必须首先解析帧头以确定传输了多少数据,是否屏蔽了数据等。对数据进行排序后,便知道流中的哪些字节要解码。 。 There's a good reference here . 有一个很好的参考这里

Basically it's more complicated than you think. 基本上,它比您想象的要复杂。 Instead of writing your own WebSocketServer, consider using some established projects: 与其编写自己的WebSocketServer,不如考虑使用一些已建立的项目:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM