tcpclient question

sde

Well-known member
Joined
Aug 28, 2003
Messages
160
Location
us.ca.fullerton
im trying to get a server/client app to work. i want my client app to read anything the server is sending it.

ive put the Stream.Read method inside a timer, but it just hangs when i run it. the exception doesnt even trigger. am i going about this wrong?
Code:
// initialization
TcpClient tcpclnt = new TcpClient();         
tcpclnt.Connect("10.10.10.10,8001);
Stream stm = tcpclnt.GetStream();

.....
this.timer1.Interval = 1000;			
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
this.timer1.Start();

...
private void timer1_Tick(object sender, System.EventArgs e)
{
  try
  {
    byte[] bb = new byte[100];
    int k = stm.Read(bb,0,100);

    for ( int i=0 ; i<k ; i++ )
      txtBox.Text += (Convert.ToChar(bb[i]));	
  }
  catch(Exception p)
  {
    MessageBox.Show(p.ToString());
  }
}

on the server side, im using this to send
Code:
Socket s = new Socket();
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("string"));
 
if the server is sending a string you could use a StreamReader to read a line at a time.
I think the problem is you are trying to read 100 bytes but only sending 6 or 7, the client is waiting for the remaining data before it returns.
 
ive researched a little more i found that the read method will wait until it gets data or an exception is generated. blocking is the term i believe.

the problem is that the server is not always sending data.
i want the client to update only when data is sent .. but when i call the read method, the entire program just hangs until it receives data.

how would i let it listen for data while the program does other things?
 
I dont use the TcpClient class myself, I use the Socket class which I believe TcpClient wraps. The Socket class has asynchronous methods to go along with the synchronous ones, and to avoid blocking you must use those instead.

The method you want is BeginRead()
 
Back
Top