0

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.

This is my first attempt, do you have any suggestions how to improve the code, or is my code complete garbage! :D

I send a Uint16 first as indicator of the message size

    // 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);
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kenion
  • 105
  • 1
  • 10

1 Answers1

0

IOCP server is good choice in this case.

There are many samples for this.

May be this one is good.

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

Good luck.

Jake
  • 129
  • 10