TcpListener only works first time

G

Greg

I've implemented the code from MS at:
http://msdn.microsoft.com/library/d...rlrfSystemNetSocketsTcpListenerClassTopic.asp
and am able to send data but it only works once. Nothing happens the second
time, not even an error.

Here's what my client function looks like:

Function SendData(ByVal Data As String) As String

Dim port As Int32 = 13000
Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")

Dim client As New TcpClient
client.Connect(localAddr, port)

Dim stream As NetworkStream = client.GetStream()

Dim msg As [Byte]() = System.Text.Encoding.ASCII.GetBytes(Data)
stream.Write(msg, 0, msg.Length)

client.Close()

End Function

Anyone know what the problem is?
 
J

Juan Romero

Yes Greg,

Every time you call this function you are initializing a new instance of the
client.
You should only initialize it once, outside somewhere, and assign bytes to
the stream every time you want to send data.
Also, although the documentation says it is not necessary, flush the stream
just to make sure everything goes as planned (stream.flush())

Good Luck.
 
G

Greg

Juan Romero said:
Yes Greg,

Every time you call this function you are initializing a new instance of the
client.
You should only initialize it once, outside somewhere, and assign bytes to
the stream every time you want to send data.
Also, although the documentation says it is not necessary, flush the stream
just to make sure everything goes as planned (stream.flush())

Good Luck.

Thanks for the reply. Stream.Flush() seems to have fixed the problem. I
can now repeatedly send data without any problem.
 
G

Guest

How could .Flush() possibly have fixed the problem???

The NetworkStream.Flush() method does nothing. The NetworkStream object represents an UNBUFFERED string. There is no buffer to .Flush(). The documentation even states this very plainly. .Flush() doesn't throw any errors, it simply does nothing

Also, in response to Juan's post - of course the code reinitializes the TcpClient each time. That's the nature of the program and that is correct. Once a request has been filled, the connection is closed and TcpListener waits for another request at which point the program calls SendData() and creates a new Client

I am having a similar problem with the NetworkStream .Write() method and have not yet found a solution. Any other (knowledgable) suggestions will be much appreciated
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top