Network Stream Reading

Straterra

New member
Joined
Mar 21, 2007
Messages
1
Programming Experience
3-5
I have an application I wrote that has a telnet interface. Now, I am trying to automate some tasks by sending socket data through this interface to the program. My client can connect and send text, but for some reason does not read anything given to it from the server. The server is expecting the stream to be read and crashes when the connection closes and the stream hasn't been read. So, I need to implement some stream reading on the client..This is what I have so far.

I was wondering if there would be some way to loop after the text is sent to see if there is data in the stream and if there is, pluck it and clear the stream so the server doesn't choke and die...


VB.NET:
        Dim Remote As String = Nothing

        Remote = InputBox("Please insert the location of the remote host.", "Refresh")
        Dim tcpClient As New System.Net.Sockets.TcpClient()
        tcpClient.Connect(Remote, 5657)
        Dim networkStream As NetworkStream = tcpClient.GetStream()
        If networkStream.CanWrite And networkStream.CanRead Then
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("refresh" & vbCrLf)
            networkStream.Write(sendBytes, 0, sendBytes.Length)

        Else
            If Not networkStream.CanRead Then
                MsgBox("cannot not write data to this stream")
                tcpClient.Close()
            Else
                If Not networkStream.CanWrite Then
                    MsgBox("cannot read data from this stream")
                    tcpClient.Close()
                End If
            End If
        End If
 
Loop until what? With sockets you work with defined communication protocols and only read/write when expected to. The protocol is defined by common standard of the networking application you operate or by yourself for your private needs when you write both server/client. If you expect one string return from what you sent you read that and finished, if you expect three strings in return from a command sent you read three times and finished, if you expect a stream of text until something you loop and read until that something is detected.

With this kind of thing you would probably wrap a streamreader and streamwriter around the networkstream when connection is made and keep these for reading/writing until it is time to disconnect, because closing any of them will also close the underlying stream.
VB.NET:
Dim sr As IO.StreamReader 
Dim sw As IO.StreamWriter 
 
sr = New IO.StreamReader(networkstream)
sw = New IO.StreamWriter(networkstream)
These classes both have methods that read/write a null-terminated string, the functions sr.ReadLine and sw.WriteLine.
 
Back
Top