C# Sockets and Multithreading

前端 未结 2 1925
后悔当初
后悔当初 2021-01-16 05:08

I am trying to learn more about sockets and threading in c#. I have come across a lot of good resources online to help get me started. The program I made so far, is a simple

2条回答
  •  [愿得一人]
    2021-01-16 05:53

    After accepting the socket in the middle man I do the following:

     private void WaitForData()
        {
            try
            {
                if (socketReadCallBack == null)
                {
                    socketReadCallBack = new AsyncCallback(OnDataReceived);
                }
    
                ReceiveState rState = new ReceiveState();
                rState.Client = mySocket;
    
                mySocket.BeginReceive(rState.Buffer, 0, rState.Buffer.Length, SocketFlags.None,
                    new AsyncCallback(socketReadCallBack), rState);
    
            }
            catch (SocketException excpt)
            {
                // Process Exception
            }
    
        }
    

    Receive State is:

    public class ReceiveState
      {
        public byte[] Buffer = new byte[1024]; //buffer for network i/o
        public int DataSize = 0; //data size to be received by the server
        public bool DataSizeReceived = false; //whether prefix was received
        public MemoryStream Data = new MemoryStream(); //place where data is stored
        public Socket Client;   //client socket
       }
    

    Once data is received my routine "OnDataReceived" processes it. I'm not experiencing any CPU problems with this.

    Same code used for both the client and middleman.

提交回复
热议问题