1

I'm making a server - client program using TcpClient and server.

To send from the server I use:

static void send(string data) { sw.WriteLine(data + Environment.NewLine); } 

And when the client connects I'm sending some text:

client = listener.AcceptTcpClient(); sr = new StreamReader(client.GetStream()); sw = new StreamWriter(client.GetStream()); string line; try { send("Hello world"); } //More code 

And to read from client:

string data; data = sr.ReadLine(); if(data != string.Empty || data != null) { MessageBox.Show(data); } 

I tried putting inside while(true) and it froze, I tried putting inside a timer tick loop and it froze...

How do I fix this?

P.S: The client and the server are 2 different projects.

5
  • What line does it freeze on? What line throws the exception that makes it crash? Commented Oct 10, 2016 at 15:39
  • Dosen't throw an exception, the program just freezes Commented Oct 10, 2016 at 15:39
  • You said you put it in "a timer tick loop and it crashed". First question still stands if you step through your code in the debugger which line does it freeze on? Commented Oct 10, 2016 at 15:41
  • Sorry It was a typo, I got the same result as with the while(true) loop, it just freezes until I close the program/server Commented Oct 10, 2016 at 15:43
  • Please use debugger to stepping through each line, and tell us at which line it executes before going hang/freeze. Commented Oct 11, 2016 at 11:39

2 Answers 2

6

I believe you need something like this:

try { listen = new TcpListener(myAddress, port); listen.Start(); Byte[] bytes; while (true) { TcpClient client = listen.AcceptTcpClient(); NetworkStream ns = client.GetStream(); if(client.ReceiveBufferSize > 0){ bytes = new byte[client.ReceiveBufferSize]; ns.Read(bytes, 0, client.ReceiveBufferSize); string msg = Encoding.ASCII.GetString(bytes); //the message incoming MessageBox.Show(msg); } } } catch(Exception e) { //e } 

Then have this code as a background thread:

Thread thread = new Thread(the functions name); thread.IsBackground = true; thread.Start(); 

I hope I understand what you need.

Sign up to request clarification or add additional context in comments.

6 Comments

I said that the client and the server are not on the same project, they are 2 different programs
You're missing a brace for your while also you should check if you got anything from the call to ns.Read elso you'll be creating a bunch of empty strings
From what you said, this seems right, maybe add more detail?
I want the server and the client to be seperate programs
Thanks, that's what I needed :)
|
1

Try this one, grandpa's way.

 int i = 0; while (stream.DataAvailable == true) { bytes[i] = ((byte)stream.ReadByte()); i++; } data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); Console.WriteLine("Received: {0}", data); 

Comments