简体   繁体   English

超过500个客户端的TCP /异步接收句柄

[英]TCP / Async Receive Handle for more then 500 clients

I am a complete beginner in the TCP section, I try to program a Master Server which should handle more then 500 clients with small delay. 我是TCP部分的一个完整的初学者,我尝试编写一个主服务器,该服务器应处理500个以上的客户端,并且延迟很小。

This is my first attempt, do you have any suggestions how to improve the code, or is my code complete garbage! 这是我的第一次尝试,您对如何改进代码有任何建议,还是我的代码完全垃圾! :D :D

I send a Uint16 first as indicator of the message size 我首先发送Uint16作为邮件大小的指示器

    // receive Code!
    private byte[] indexBuffer = new byte[sizeof(UInt16)];
    private int indexSize = sizeof(UInt16);

    public async void receiveData(TcpClient client) {
       var result = await Task.Run(() => {
           try {
               int checkSum = client.Client.Receive(indexBuffer, 0, indexBuffer.Length, SocketFlags.None);
               if (checkSum != indexSize) return null;

               int packageSize = BitConverter.ToUInt16(indexBuffer, 0);
               Console.WriteLine(packageSize);
               var recData = new Byte[packageSize];

               checkSum = client.Client.Receive(recData, 0, packageSize, SocketFlags.None);
               if (checkSum != packageSize) return null;
               return Encoding.ASCII.GetString(recData);
           } catch(Exception ex) {
               Console.WriteLine(ex.Message);
               return "-1";
           }
        });

        // blabla do something 
        Console.WriteLine(result);

        //---------------------
        if (client.Connected) 
           receiveData(client);
    }

IOCP server is good choice in this case. 在这种情况下,IOCP服务器是不错的选择。

There are many samples for this. 有很多示例。

May be this one is good. 可能这是一件好事。

https://www.codeproject.com/Articles/832818/EpServerEngine-cs-A-lightweight-asynchronous-IOCP https://www.codeproject.com/Articles/832818/EpServerEngine-cs-A-lightweight-asynchronous-IOCP

Good luck. 祝好运。

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

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