TCPClient problems

W

WildBill

I am using a tcpclient and a network stream to communicate with the TCP
port on a printer for testing the printer firmware.
The code I have works perfectly the first time I run it. The printer
reacts correctly.
If I run it again there is a long delay before the the printer reacts.

When we used VB6 sockets to do this we had no problems.
Below is the code I am using in Visual Studio 2005
Any help would be appreciated.

Public Function SendReceive(ByVal strMechCommand As String, _
ByRef strReturnedData As
String) As Boolean
'--- Create a TcpClient ---
Try
printer = New TcpClient(mIPAddress, Port)
printer.NoDelay = True
mConnected = True
'--- Get a client stream for reading and writing ---
stream = printer.GetStream()

Catch er As Exception
mErrorMessage = er.Message
Try
stream.Dispose()
printer.Close()
Catch err As Exception
mErrorMessage = mErrorMessage & vbCrLf & "No
Connections to close."
End Try
End Try

'--- If the printer is connected
If printer.Connected And stream.CanWrite And stream.CanRead
Then
Try
Dim mechCommand As [Byte]() =
System.Text.Encoding.ASCII.GetBytes(strMechEnter & strMechCommand &
strMechExit)
stream.Write(mechCommand, 0, mechCommand.Length)
Thread.Sleep(300)
'--- If return data is expected then go get it ---
If strReturnedData <> "SendOnly" Then
'--- Create variable to create a Buffer to
store the response bytes ---
Dim received_data = New [Byte](1024) {}
'--- Create a string to store the response
ASCII representation ---
Dim received_string As [String] =
[String].Empty
'--- Create a variable to store the number of
bytes received ---
Dim bytes As Int32
'--- Create a counter variable ---
Dim count As Integer = 0
'--- Loop that waits for upto 4 seconds for
data to be returned --
While stream.DataAvailable = False
Thread.Sleep(100)
count += 1
If count > 40 Then
mErrorMessage = "Timeout while waiting
for data."
Disconnect()
Exit Function
End If
End While
'--- Loop that reads data 1024 bytes at a time
till all data received ---
While stream.DataAvailable
bytes = stream.Read(received_data, 0,
received_data.Length)
received_string +=
System.Text.Encoding.ASCII.GetString(received_data, 0, bytes)
Thread.Sleep(500)
End While
Disconnect()
strReturnedData = received_string
Else
Disconnect()
strReturnedData = ""
End If
Return True
Catch err As Exception
mErrorMessage = err.Message
Disconnect()
Return False
End Try
Else
mErrorMessage = "SendReceive method: No Connection to
printer found"
mConnected = False
Disconnect()
Return False
End If
End Function
 

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