[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 845
  • Last Modified:

C# Network Program hangs

I got a question about my first C# networking program. I have a server and a client program, and the server just sends out numbers to the client. I don't just want the client to receive but to send also. For example, to create commands to send only odd/even numbers, or numbers in some range.

My server program is multithreaded and it goes like this:

while true
   SocketComm socObj = new SocketComm();
   sockObj.dummySocket = tlsserver.AcceptSocket();
   Thread thd = new Thread(new ThreadStart(sockObj.ThreadProc));
   thr.IsBackground = true;

public void ThreadProc()
   NetworkStream serverSockStream = new NetworkStream(mySocket);
   StreamReader serverStreamReader = new StreamReader(serverSockStream);
   StreamWriter serverStreamWriter = new StreamWriter(serverSockStream);

   Random random = new Random();

     int randomNumber.Next(1000);
        // This works fine and sends the numbers to client like expected
        // Client times out when I add this line:
       //  string returndata = serverStreamReader.Readline();
     { break; }

In the client, I connect to the server like this:

   private void ConnectToServer(string ServerIP, int ServerPort)
            // Create a new instance of a TCP client
            tcpClient = new TcpClient();
                // Connect the TCP client to the specified IP and port
                tcpClient.Connect(ServerIP, ServerPort);
                NetworkStream clientSockStream = tcpClient.GetStream();
                clientStreamReader = new StreamReader(clientSockStream);
                clientStreamWriter = new StreamWriter(clientSockStream);

and when I click 'Get Number" in the form, these are the important lines:
string returndata = clientStreamReader.ReadLine();

And when I want to send something to the server, I have this line:

Now, the problem is, the client hangs if I add this line to read in the while loop of ThreadProc in the server:

string returndata = serverStreamReader.Readline();

Why does the client hang? How do I get the server to also read from a stream?

1 Solution
I think it would be easier to use asynchronous reading on your networkStream instead.
I don't believe the ReadLine() is a blocking call, so you cannot be sure there is any data there when your code hits that point.

Have a read on the NetworkStream's BeginRead

Featured Post

Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now