因此,我决定通过给自己做一些有趣的任务来开始学习它。
作为一名Web开发人员,我希望拥有自己的WebSocket服务器。
所以我已经写了它,但它只接受第一个请求。之后,在onflow上进行算术运算。
这是一些代码,供您查看我在做错什么:S我真的没有主意。

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

using WebSocket.Utils;

namespace WebSocket
{
    class SocketReader
    {
        public EndPoint ipAddr { get; set; }
        private Socket userSocket;
        private byte[] buffer;
        private string SOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

        public SocketReader(Socket socket)
        {
            userSocket = socket;
            ipAddr = socket.RemoteEndPoint;
            Read();
        }

        private void Read()
        {
            //Read packet size
            buffer = new byte[2];
            userSocket.BeginReceive(buffer, 0, 2, SocketFlags.None, ReadCallbackStatic, null);
        }

        private void ReadCallbackStatic(IAsyncResult ar)
        {
            try
            {
                if (userSocket.EndReceive(ar) >= 1)
                {
                    int bufferSize = BitConverter.ToInt16(buffer, 0);
                    buffer = new byte[bufferSize - 2];
                    //Read Packet
                    userSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReadCallback, null);
                }
            }
            catch (Exception se)
            {
                Console.WriteLine("Something blew on ReadCallbackStatic");
                Console.WriteLine(se.Message);
                Console.WriteLine(se.StackTrace);
                Disconnect();
            }
        }

        private void ReadCallback(IAsyncResult ar)
        {
            try
            {
                //Copy the buffer so we can receive the next packet ASAP
                byte[] buff = new byte[buffer.Length];
                Array.Copy(buffer, buff, buffer.Length);
                Read();

                string handshakeStr = System.Text.Encoding.UTF8.GetString(buff);
                string[] list = Regex.Split(handshakeStr, "\r\n");

                //Sec-WebSocket-Key: S5o6fCVLRMJhdXTF3H9w3Q==
                //Sec-WebSocket-Version: 8

                string key = "";
                string clientProtocol = "0";

                foreach (string str in list)
                {
                    if (String.IsNullOrEmpty(str)) { continue; }
                    if (str.Length > 20 && str.Substring(0, 19) == "Sec-WebSocket-Key: ")
                    {
                        key = str.Substring(19);
                        continue;
                    }

                    if (str.Length > 20 && str.Substring(0, 23) == "Sec-WebSocket-Version: ")
                    {
                        clientProtocol = str.Substring(23);
                        continue;
                    }
                }

                if (String.IsNullOrEmpty(key))
                {
                    Disconnect();
                }

                SHA1 shaEnc = new SHA1CryptoServiceProvider();

                byte[] byteString = ASCIIEncoding.ASCII.GetBytes(key + SOCKET_GUID);
                byte[] hash = shaEnc.ComputeHash(byteString, 0, byteString.Length);
                string acceptKey = Convert.ToBase64String(hash);

                List<string> headers = new List<string>();
                headers.Add("HTTP/1.1 101 Switching Protocols");
                headers.Add("Upgrade: websocket");
                headers.Add("Connection: Upgrade");
                headers.Add("Sec-WebSocket-Accept: " + acceptKey);

                foreach (string header in headers)
                {
                    SendString(header + "\r\n");
                }

                Console.WriteLine(acceptKey);

                SendString("\r\n");

            }
            catch (SocketException se)
            {
                Console.WriteLine("Something blew on ReadCallback");
                Console.WriteLine(se.Message);
                Disconnect();
            }
        }

        private void SendString(string str)
        {
            userSocket.Send(Encoding.UTF8.GetBytes(str));
        }

        private void Disconnect()
        {
            userSocket.Disconnect(false);
            Console.WriteLine("Client with ip {0} Disconnected", ipAddr);
        }
    }
}

它是我类(class)的简化版本,但困扰我的问题出现在此行的“ReadCallbackStatic”中:
buffer = new byte[bufferSize - 2];

我真的不知道我在做什么错:S。
问题是...我实际上已经正确握手,但是当我从客户端向服务器发送一些信息时,会抛出此异常

我进行了一些调试,看来缓冲区变量以某种方式变为负数O.O

最佳答案

我的猜测是,当设置了MSB时,您正在大惊小怪,例如,客户端正在发送一个> = 32768和ToInt16)正变成一个很大的负16位数字(或者,或者,引发算术溢出问题)。我会尝试使用ToUInt16代替。

老实说,您这里确实不需要BitConverter;根据字节顺序,这可以是:

int bufferSize = (buffer[0] << 8) | buffer[1];

或者
int bufferSize = buffer[0] | (buffer[1] << 8);

关于c# - 在C#中读取套接字时,算术运算溢出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8036053/

10-11 14:11