Link to home
Start Free TrialLog in
Avatar of igor92128
igor92128

asked on

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;
   thr.Start();
   thr.Sleep(750);
}

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

   Random random = new Random();

   while(true)
   {
     int randomNumber.Next(1000);
   
     try
     {
        // This works fine and sends the numbers to client like expected
        serverStreamWriter.WriteLine(randomNumber);
        // Client times out when I add this line:
       //  string returndata = serverStreamReader.Readline();
     }
     catch
     { 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();
            try
            {
                // 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();
lbparam.Items.Add(returndata);
...

And when I want to send something to the server, I have this line:
clientStreamWriter.WriteLine(myCommandToServer);


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?

Thanks,
Igor
ASKER CERTIFIED SOLUTION
Avatar of PockyMaster
PockyMaster
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial