Auto read from network stream when new data is written

TheGrange

Member
Joined
Jan 2, 2009
Messages
7
Programming Experience
Beginner
Hi, Im working on an instant messenger form within another larger application. I have managed to establish a working TCP/IP connection between client and server using TcpListener and an initial message saying connection is established is sent between the two and displayed in a rich text box (called "Chatbox.Display" on either machine:

Const portnumber As Integer = 8000
Dim localAddr As IPAddress
localAddr = System.Net.Dns.GetHostAddresses(My.Computer.Name)(0)
Dim tcplistener As New TcpListener(localAddr, portnumber)
tcplistener.Start()

'Accept the pending client connection and return a TcpClient initialized for communication.

Dim tcpClient As TcpClient = tcplistener.AcceptTcpClient()
ChatBox.Display.AppendText("Connection accepted.")
' Get the stream
networkStream = tcpClient.GetStream()
' Read the stream into a byte array
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))

Dim clientdata As String = Encoding.ASCII.GetString(bytes)
ChatBox.Display.AppendText(clientdata)
Dim responseString As String = "Connected to server"
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)


This is all fine but now that I have an open Tcp connection I don't understand how to get one machine to automatically read from the networkstream every time the other machine writes to it. Is there an event that can be raised by new data being written by the remote computer?

I want to try to avoid having a loop which just constantly checks if data is available (using the DataAvailable property) and reads if true because I am running other parts of the App and want to reserve memory for that.

Thanks very much
 
The alternatives are:
  • Loop to poll for data available.
  • Use a Timer to poll for data available.
  • Start an asynchronous read operation even if there is no data, it will return when there is data, or throw exception if connection is broken.
I want to try to avoid having a loop ... because I am running other parts of the App
I think you mean threading here, multithreading is needed in socket programming.

I would normally prefer loop & poll in a thread, sleeping thread suffiently between loops.
 
Okay, thanks for the reply :). I was thinking about the timer option, it may be the best solution. How do you think something like MSN messenger does this? Is there a standard method? Or do network comm programs normally just try read on a constant loop?

Many thanks

grange
 
Back
Top