1

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 ();
    }
}

2 Answers 2

3

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.");
  }
Sign up to request clarification or add additional context in comments.

6 Comments

MSDN is your best friend
Hey thank you! And what determines that a network stream can read?
@redigaffi I naturally assume it means that the TCP connection stays open.
Thank you, now i understand, so i should add in the receiveData a while loop which condition is strem.CanRead and inside an conditional to check stream.DataAvailable? this should be the correct to way for avoiding trying reading data if nothing is there. Thank you very much!
@redigaffi yes, just like the sample code. Mark this as answer?
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.