简体   繁体   中英

C# Multithreading socket server receiving data

I have developed this small multi-threaded socket server, that creates one socket to not block the main program, and another thread for each new accepted connection.

The question comes when reading the data, I have a method called receiveData that reads all the data input, so right now the code only reads one time for each connection.

I solved this by adding inside the method receiveData a while loop with the flag socket.CanRead , what does this flag exactly do? What difference is there between CanRead and DataAvailable ?

class Server
{
    static void receiveData(TcpClient client, NetworkStream stream)
    {
        byte[] bytes = new byte[client.ReceiveBufferSize];
        stream.Read (bytes, 0, (int) client.ReceiveBufferSize);
        string returndata = Encoding.UTF8.GetString (bytes);
        Console.WriteLine ("SERVER RECEIVED: " + returndata);              
    }

    static void startServer()
    {
        new Thread(() =>
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 5000);
            listener.Start();

            while (true)
            {
                if (listener.Pending()) {
                    new Thread(() =>
                    {
                        TcpClient client = listener.AcceptTcpClient();
                        NetworkStream stream = client.GetStream();
                        Server.receiveData(client, stream);
                    }).Start();
                }  
            }
        }).Start();
    }

    static void Main(string[] args)
    {
        Server.startServer ();
    }
}

Refer to MSDN NetworkStream.CanRead Property ,

CanRead:

Gets a value that indicates whether the NetworkStream supports reading.

while DataAvailable:

Gets a value that indicates whether data is available on the NetworkStream to be read.

It's like incoming data will be indicated as available only if the NetworkStream supports reading, thus can be read.

Take a look at sample code, I think it will answer all of your questions:

 // Examples for CanRead, Read, and DataAvailable.

  // Check to see if this NetworkStream is readable.
  if(myNetworkStream.CanRead){
      byte[] myReadBuffer = new byte[1024];
      StringBuilder myCompleteMessage = new StringBuilder();
      int numberOfBytesRead = 0;

      // Incoming message may be larger than the buffer size.
      do{
           numberOfBytesRead = myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
           myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));

      }
      while(myNetworkStream.DataAvailable);

      // Print out the received message to the console.
      Console.WriteLine("You received the following message : " +
                                   myCompleteMessage);
  }
  else{
       Console.WriteLine("Sorry.  You cannot read from this NetworkStream.");
  }

According to MSDN documentation NetworkStream.CanRead Can Read MSDN is used to determine if network stream is support reading. NetworkStream.DataAvailable Data Acalible MSDN shows you if there is data to read right now. So you should use NetworkStream.CanRead to determine if it is readable, and use NetworkStream.DataAvailable to determine if there is something to be read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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