errors communicating with MT Scale over TCP/IP - Getting close - vb.net

I am using VB.net 2015 to try to communicate with a scale. I have somethings working where i can talk to scale a bit but i get random vb.net errors. Also most of the time I send the command and i get and error back from the scale so i send it again and the scale responds correctly and then i get a second response of an error.
It feels like the message i am trying to send is not getting there in one piece so i have to send it twice. Any help is great appreciated. i have so many hours into trying to make it work i am going blind.
Still learning and this is my first project using TCPClient and NetworkStream
Imports System.Net.Sockets
Public Class Form1
'Private ClientWritter As TCPControlWritter
'Public Client As TcpClient
Private port As Int32 = 1701
Private client As TcpClient
Dim stream As Net.Sockets.NetworkStream
'opens connection
Sub OpenConnection(ByVal server As [String])
Try
client = New TcpClient(server, port)
client.ReceiveTimeout = 200
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
'closes connection
Sub CloseConnection()
Try
If stream IsNot Nothing Then
stream.Close()
stream = Nothing
End If
client.Close()
client = Nothing
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
'takes the text from textbox and sends it to scale
Sub SendMesssage(ByVal message As [String])
Try
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message & vbCrLf)
' Get a client stream for reading and writing.
If stream Is Nothing Then stream = client.GetStream()
' Send the message to the connected TcpServer.
If stream.CanWrite Then
stream.Write(data, 0, data.Length)
stream.Flush()
End If
Debug.WriteLine("Sent: " & message)
' Receive the TcpServer.response.
' Buffer to store the response bytes.
data = New [Byte](256) {}
' String to store the response ASCII representation.
Dim responseData As String = ""
If stream.CanRead Then
' Read the first batch of the TcpServer response bytes.
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
Debug.WriteLine(responseData)
End If
Catch e As ArgumentNullException
Debug.WriteLine("ArgumentNullException: {0}", e)
Catch e As SocketException
Debug.WriteLine("SocketException: {0}", e)
End Try
txtMessage.Text = ""
txtMessage.Focus()
End Sub
'here is the data i get back from the scale. The "sent" lines are my input.
53 Ready for user
>
Sent: user admin
83 Command not recognized
>
83 Command not recognized
>
Sent: user admin
12 Access OK
>
83 Command not recognized
>

Related

Vb.net application connect to multiple server via TCP/IP

I made a Winforms application to work with 4 different machines by connecting with them via TCP/IP. Somehow, the connection sometimes seems disconnected and reconnecting after a short while. May I know is it I used too much TCP client and caused them congested??
Below is the function/method to connect those machine...with 4 of them different function names to connect each of the machine, but the code is more or less the same:
Public Async Sub connect_Machine_Ethernet(ByVal mainForm As Form1)
If Machine_COMPort.IsOpen Then
Machine_COMPort.Close()
End If
If (IsNothing(Machine_client)) Then
'do nothing, since obj is not created
Else
Try
Machine_client.GetStream.Close()
Machine_client.Close()
Catch exp As Exception
End Try
End If
Try
Machine_client = New TcpClient
Machine_client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, True)
Dim result = Machine_client.BeginConnect(Machine_ModuleIP_txt.Text, CInt(Machine_ModulePort_txt.Text), Nothing, Nothing)
result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1))
Machine_client.GetStream.BeginRead(Machine_ethernet_buffer, 0, Machine_ethernet_buffer.Length, AddressOf Machine_TCP_read, Machine_ethernet_buffer)
DisplayMsg("Machine Ethernet connection established")
manual_connection_LED.StateIndex = 3
Machine_client_isConnected = True
Machine_TCP_Reconnect_btn.Invoke(Sub() Machine_TCP_Reconnect_btn.Visible = False)
Catch ex As Exception
DisplayMsg("Error : Unable to connect to the Machine Ethernet connection")
manual_connection_LED.StateIndex = 0
Machine_client_isConnected = False
If (IsNothing(Machine_client)) Then
'do nothing, since obj is not created
Else
Try
Machine_client.GetStream.Close()
Machine_client.Close()
Catch exp As Exception
End Try
End If
End Try
End Sub
'Read Machine TCP message
Sub Machine_TCP_read(ByVal ar As IAsyncResult)
Try
Dim buffer() As Byte = ar.AsyncState
Dim bytesRead As Integer = Machine_client.GetStream.EndRead(ar)
Dim Message As String = System.Text.Encoding.ASCII.GetString(Machine_ethernet_buffer, 0, bytesRead)
If Message = "" Then
'----check connection
If Machine_client.Connected Then
Machine_client.Close()
connect_Machine_Ethernet(Me)
End If
Else
DisplayMsg("Input Received from machine : " & Message)
Process_machine_Feedback(Message) 'perform any data logic from the message
Machine_client.GetStream.BeginRead(Machine_ethernet_buffer, 0, Machine_ethernet_buffer.Length, AddressOf Machine_TCP_read, Machine_ethernet_buffer)
End If
Catch ex As Exception
DisplaySystemMsg(ex.Message)
DisplayMsg("Marking machine Ethernet disconnected from the server")
manual_connection_LED.StateIndex = 0
Machine_client_isConnected = False
Exit Sub
End Try
End Sub
'Send message to TCP
Public Sub Machine_TCP_send(ByVal str As String)
Try
sWriter = New StreamWriter(Machine_client.GetStream)
sWriter.WriteLine(Chr(2) & str & Chr(3)) 'add prefix suffix
sWriter.Flush()
DisplayMsg("Message send to the machine via TCP: " & str)
Catch ex As Exception
DisplayMsg("Error : Message failed to send to themachine!")
End Try
End Sub

vb.net weight scale tcpip not getting data

i am new to vb.net 2008 to get data from weigh scale using tcpclient(). below mentioned code is able to connect with machine but not getting the data. But hyperterminal is able to get data.
I searched most of the post but may coding exist only for serial port connection.
Output MsgBox :
Received: {0}
Imports System.Net.Sockets
Public Sub Connect(ByVal server As [String], ByVal _Ports As Int32, ByVal message As [String])
Try
' Create a TcpClient.
' Note, for this client to work you need to have a TcpServer
' connected to the same address as specified by the server, port
' combination.
Dim port As Int32 = _Ports
Dim client As New TcpClient()
'Dim client As New TcpClient(server, port)
client.Connect(server, port)
If client.Client.Connected Then TextBox3.Text = "Connected"
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
Dim stream As NetworkStream = client.GetStream()
Dim Buffer(client.ReceiveBufferSize) As Byte
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
'Console.WriteLine("Sent: {0}", message)
MsgBox("Sent: {0} " & message)
' Receive the TcpServer.response.
' Buffer to store the response bytes.
data = New [Byte](2047) {}
'MsgBox("Response Byte - " & data.Length)
' String to store the response ASCII representation.
Dim responseData As [String] = [String].Empty
' Read the first batch of the TcpServer response bytes.
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
'Console.WriteLine("Received: {0}", responseData)
MsgBox("Received: {0} " & responseData)
' Close everything.
stream.Close()
client.Close()
Catch e As ArgumentNullException
'Console.WriteLine("ArgumentNullException: {0}", e)
MsgBox("ArgumentNullException: {0}" & e.Message)
Catch e As SocketException
'Console.WriteLine("SocketException: {0}", e)
MsgBox("SocketException: {0}" & e.Message)
End Try
MsgBox("Got to this point in code")
'Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")
'Console.Read()
End Sub
This:
MsgBox("Received: {0} " & responseData)
...does not automatically replace {0} with the value of responseData.
The {0} placeholder is used with the String.Format() function. Change your code to this, in all applicable places, and check the result:
' Let's also get rid of the legacy VB6 MsgBox() function:
MessageBox.Show(String.Format("Received: {0} ", responseData))
Also, what's with the square brackets around some data types (i.e. [String])? They aren't needed.

My program can't read an ASCII string from TCP connection, keeps looping

I'm connecting to a specific TCP port of a server, do stuff, and I need to disconnect at some point, then wait for the server to open its port again and reconnect.
My program loops forever.
To disconnect from the server, I sent from the server the string "TCP:OFF" and the close the port (server side). Whenever my program reads this line, I want it to close its connection and wait the server to open its port again. This is because of the TCP/IP protocol.
The problem is that the specific ASCII string sent from my server is not read until I put my mouse over my window (weird). At the end, I want my program to work by itself and minimized, without human intervention.
There must be a problem in the timing of my networkStream reading.
Code
While tcpClient.Connected() = False
Try
tcpClient.ReceiveTimeout = 1000
tcpClient.SendTimeout = 1000
tcpClient.Connect("192.168.10.100", 10003)
Console.WriteLine("Connection OK")
System.Threading.Thread.Sleep(1000)
Catch ex As Exception
Console.WriteLine("ERRORR : Server unreachable")
System.Threading.Thread.Sleep(1000)
End Try
End While
Dim networkStream As NetworkStream = tcpClient.GetStream()
If networkStream.CanRead And networkStream.DataAvailable Then
Try
ReadData = ""
Dim myReadBuffer As Byte() = New Byte(7) {}
Dim numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length)
ReadData = Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead)
Console.Write(ReadData & vbCrLf)
Catch ex As Exception
Console.Write("Error reading data")
End Try
End If
If ReadData = "TCP:OFF" Then
tcpClient.Close()
ReadData = ""
Console.WriteLine("Closing connection")
System.Threading.Thread.Sleep(5000)
tcpClient = New TcpClient
End If
I'm doing a Windows form program in latest Visual Studio.

Udpclient sometimes throws exception

I'm currently working on a UDP communication PC <-> ARM LM3S6965 (Luminary) through the Ethernet. On the PC there is a VB.net application that simulates a UDP server/client.
the message is broadcasted from Vb.net application to ARM LM3S6965 based device, and in return response is sent from ARM Device to vb.net application.
but sometimes receive UdpClient throws socket exception i.e. Only one usage of each socket address (protocol/network address/port) is normally permitted.
the line which throws exception is
udpReceivingClient = New UdpClient(mnPort)
Complete VB.net Code is as follows
Module mod_Search_UDP
Public mnPort As Int32 = 3040 'Port number to send/recieve data on
'Public Const msBroadcastAddress As String = "255.255.255.255" 'Sends data to all LOCAL listening clients, to send data over WAN you'll need to enter a public (external) IP address of the other client
'Dim endPoint As IPEndPoint = New IPEndPoint(msBroadcastAddress, mnPort)
Public udpReceivingClient As UdpClient 'Client for handling incoming data
Public udpSendingClient As UdpClient 'Client for sending data
Public receivingThread As Thread 'Create a separate thread to listen for incoming data, helps to prevent the form from freezing up
Public mbiClosing As Boolean = False 'Used to close clients if form is closing
Public mbiCloseRxClient As Boolean = False
Public Sub InitializeSender()
Dim soc As Socket
Dim lsPort As String
Dim lnPort As Int32 = 3040
Const lsBroadcastAdd As String = "255.255.255.255"
'Dim endPoint As IPEndPoint = New IPEndPoint(msBroadcastAddress, mnPort)
'udpSendingClient = New UdpClient(endPoint)
udpSendingClient = New UdpClient(lsBroadcastAdd, lnPort)
udpSendingClient.EnableBroadcast = True
soc = udpSendingClient.Client
lsPort = (CType(soc.LocalEndPoint, IPEndPoint).Port.ToString())
mnPort = Convert.ToInt32(lsPort)
End Sub
Public Sub InitializeReceiver()
'Create UdpClient class and bind it to the local port number provided
'Try
udpReceivingClient = New UdpClient(mnPort)
'udpReceivingClient.EnableBroadcast = True
mbiCloseRxClient = True
'Catch ex As Exception
' MsgBox(ex.ToString)
'End Try
Dim start As ThreadStart = New ThreadStart(AddressOf MT_Receiver)
receivingThread = New Thread(start)
receivingThread.IsBackground = True
receivingThread.Start()
End Sub
Public Sub MT_Receiver()
Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, mnPort) 'Listen for incoming data from any IP address on the specified port
Dim lbData() As Byte 'Buffer for storing incoming bytes
Dim llRet As UInt16
'udpListen.Poll(1000, Net.Sockets.SelectMode.SelectRead)
While (True) 'Setup an infinite loop
If mbiClosing = True Then 'Exit sub if form is closing
Exit Sub
End If
llRet = udpReceivingClient.Available
If llRet > 0 Then
lbData = udpReceivingClient.Receive(endPoint) 'Receive incoming bytes
'If udpListen.Available Then
' udpListen.Receive(lbData, 256, Net.Sockets.SocketFlags.None)
'End If
'If lbData Is Nothing Then
'Else
frmSearchUDP.MT_Validate_Msg(lbData)
End If
End While
End Sub
Public Sub MT_Send_UDP(ByVal lbTxBuffer() As Byte)
InitializeSender()
If mbiCloseRxClient = True Then
receivingThread.Abort()
udpReceivingClient.Client.Dispose()
udpReceivingClient.Close()
End If
Try
udpSendingClient.Send(lbTxBuffer, lbTxBuffer.Length)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
udpSendingClient.Client.Dispose()
udpSendingClient.Close()
InitializeReceiver()
'Try
' udpReceivingClient.BeginReceive(AddressOf MT_RX_Callback, Nothing)
'Catch ex As Exception
' MsgBox(ex.ToString)
'End Try
End Sub
End Module
Whats mistake is there in code ? how can i use same port for receive and transmit ?

My program "stuck in this line" reading stream

This
So I am reading a stream like usual. Then it just stuck. It doesn't throw exception or anything. It just stucks.
Try
Do
read = stream.Read(datain, 0, datain.Length) 'Stuck here
responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
finalResponse = finalResponse + responseData
Loop While read > 0
Catch ex As Exception
What should I do so that the program would never get stuck like that? Notice I already put the code inside try catch block
Here is the full program.
Public Function getWhoisInfoAsText4(strDomainName As String, whoisServerToTry As String) As String
'testAsisWhois()
Dim data = System.Text.Encoding.ASCII.GetBytes(strDomainName & Microsoft.VisualBasic.vbCr & Microsoft.VisualBasic.vbLf)
Dim finalResponse = String.Empty
Dim client As TcpClient
Try
client = New TcpClient(whoisServerToTry, 43)
Catch ex As Exception
Return ""
End Try
Dim stream = client.GetStream()
Using stream
stream.Write(data, 0, data.Length)
Dim datain = New Byte(254) {}
Dim responseData = String.Empty
Dim read As Integer
Try
Do
read = stream.Read(datain, 0, datain.Length)
responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
finalResponse = finalResponse + responseData
Loop While read > 0
Catch ex As Exception
End Try
End Using
If finalResponse.Contains("Name Server:") Then
appendToTextFile(whoisServerToTry + vbNewLine, "appendfiles", Scripting.IOMode.ForAppending)
End If
finalResponse += (whoisServerUsed + whoisServerToTry + vbNewLine)
Return finalResponse
End Function
does your program stuck at the first loop sequence?
According to MSDN mabye this should help
Dim numBytesRead as Integer = 0
Do
read = stream.Read(datain, numBytesRead, datain.Length)
responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
finalResponse = finalResponse + responseData
numBytesRead += read
Loop While read > 0
Stream.Read waits always until the amount of bytes it is expecting is coming, if there is an interruption on the communication just in the moment the program is exactly on the Read and the connection get close the program will be forever in this point waiting for the rest of the bytes to come unless you will configure a ReadTimeout, then after not receiving any bytes during this time it will throw an exception.
You should then make a try catch and restart the connection.