接受websocket使用tcp .net非常慢?

时间:2014-04-15 07:22:15

标签: c# sockets tcp websocket

我使用websocket服务器创建了一个.NET类套接字。当我的浏览器尝试连接到我的程序上的套接字时,我看到方法'接受套接字'我的浏览器连接后调用非常慢或几秒钟。我尝试创建了许多连接,但套接字每秒都接受一个websocket。我也尝试了alchemy websocket,结果就像我的代码。

在IIS8上使用Miscrosoft websocket之后,我注意到速度非常好。

我不是实验性的。

我的代码(快递)

class Connection
{
    byte[] buffer = new byte[1024];
    Socket socket;
    bool IsAuthencation;
    public Connection(Socket socket)
    {
        this.socket = socket;
        socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
    }

    void OnReceive(IAsyncResult result)
    {
        try
        {
            int count = socket.EndReceive(result);
            if (count != 0)
            {
                if (!IsAuthencation)
                {
                    byte[] tmp = new byte[count];
                    Array.Copy(buffer, 0, tmp, 0, count);
                    string Request = Encoding.UTF8.GetString(tmp);
                    if (Request.Contains("GET"))
                    {
                        if (!IsAuthencation)
                        {
                            int indexStart = Request.IndexOf("Sec-WebSocket-Key: ");
                            int indexEnd = Request.IndexOf("Sec-WebSocket-Version:");
                            string key = Request.Substring(indexStart + 19, indexEnd - indexStart - 21);
                            string magic = string.Concat(key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
                            string base64 = "";
                            using (SHA1 sha1 = SHA1.Create())
                            {
                                byte[] bufferMagic = sha1.ComputeHash(Encoding.UTF8.GetBytes(magic));
                                base64 = Convert.ToBase64String(bufferMagic);
                            }

                            Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
                                + "Connection: Upgrade" + Environment.NewLine
                                + "Upgrade: websocket" + Environment.NewLine
                                + "Sec-WebSocket-Accept: " + base64
                                + Environment.NewLine
                                + Environment.NewLine);
                            socket.BeginSend(response, 0, response.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
                            IsAuthencation = true;
                        }
                    }
                }
                socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
            }
            else
            {
                // disconnect
            }
        }
        catch (Exception)
        {

        }
    }

    void OnSend(IAsyncResult result)
    {
        try
        {
            socket.EndSend(result);
        }
        catch (Exception)
        {

        }
    }

}
class Program
{
    static List<Connection> clients;
    static Socket socket;

    static void Main(string[] args)
    {
        clients = new List<Connection>();
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 30000);
        socket.Bind(endPoint);
        socket.Listen(0);
        socket.BeginAccept(new AsyncCallback(AcceptAsync), null);
        Console.ReadLine();
    }

    static void AcceptAsync(IAsyncResult result)
    {
        Console.WriteLine("a new connection");
        Socket s = socket.EndAccept(result);
        clients.Add(new Connection(s));
        socket.BeginAccept(new AsyncCallback(AcceptAsync), null);
    }


}

你可以尝试命令javascript var socket = new WebSocket(&#34; ws:// localhost:30000&#34;),我的代码中没有看到问题。 感谢

1 个答案:

答案 0 :(得分:0)

你必须接受套接字,并异步处理它,然后再回到接受更多的套接字。

<强>更新

看到您的代码后,您似乎异步接受连接。你是如何创建这些测试连接的?如果你创造的太多,你可能会使应用程序饱和。

我想我看到了问题,为什么要将socket backlog设置为0?从SO中读取this answer

尝试设置更大的值:socket.Listen(100);