Search code examples
c#tcpclientstreamreader

C# Reading stream from TcpClient


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.


Solution

  • 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.