vb.net weight scale tcpip not getting data - vb.net

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.

Related

TCP Socket doesn't send all the data

I'm trying to send about 250KBytes but I get cut at 8KBytes
I doesn't need any answer from the remote server.
I don't understand what I'm doing wrong.
Is like the tx doesn't change the outbuffer size.
Private Function SendReport7B(ByVal Msg As String, ByVal Host As String, ByVal Port As String) As String
Try
Dim Msgs() As String
Dim Tx As New TcpClient()
Dim stream As NetworkStream = Nothing
Dim LingerMode As New LingerOption(True, 1)
'Dim BSize As Integer
Tx.NoDelay = True
Tx.LingerState = LingerMode
Tx.SendTimeout = 5000
If Msg.Length > Tx.SendBufferSize Then
Tx.SendBufferSize = Msg.Length + 256
End If
Tx.Connect(Host, Port)
Msgs = Msg.Split(Chr(10))
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(Msg)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
stream = Tx.GetStream()
'stream.WriteTimeout = 100
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
Tx.Close()
Return "OK" 'responseData
Catch ex As Exception
Return "Error: " & ex.Message
End Try
End Function

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

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
>

There's a way know when a TCP payload ends?

I have a routine that sends data over TCP and must wait a response on the same opened socket.
The data to be receiver doesn't fit in one TCP message, so, the question is This code will wait until the last byte or should I must to add some indication at the end?
Private Function SendReport(ByVal Msg As String, ByVal Host As String, ByVal Port As String) As String
Try
Dim Tx As New TcpClient()
Dim stream As NetworkStream = Nothing
Dim CloseStream As Boolean = False
Dim LingerMode As New LingerOption(True, 5)
' String to store the response ASCII representation.
Dim responseData As [String] = [String].Empty
Tx.NoDelay = True
Tx.LingerState = LingerMode
Tx.SendTimeout = 10000
Tx.ReceiveTimeout = 10000
Tx.Connect(Host, Port)
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(Msg)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
stream = Tx.GetStream()
CloseStream = True
'stream.WriteTimeout = 100
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
'Tx.Connected
' Receive the TcpServer.response.
' Buffer to store the response bytes.
data = New [Byte](256) {}
' 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)
If CloseStream = True Then
stream.Close()
End If
Tx.Close()
Return responseData
Catch ex As Exception
WriteRTBLog(ex.Message, Color.Red)
WriteRTBLog(ex.StackTrace, Color.DarkRed)
Return "Error"
End Try
End Function
I never made an application to receive more than one TCP packet before, so I don't know what to expect.
The longer data that I must to expect is about 524KB

TCPClient / Server - How to Send Data via TCP/IP ASCII Special Characters

I have an application which currently sends requests via TCP/IP Port 6000, and waits for a Reply.
I have been given the Request / Reply Protocol, but cant seem to send ASCII Control Characters like SOH,SOT,EOT etc... 01,02,03.
This is what I receive via TCP Port 6000 which I can display in the Msgbox.
Enquiry Message http://www.hcs-it.com/Enquiry.jpg
And this is what I am meant to send back ...
Enquiry Message http://www.hcs-it.com/Response.jpg
Here is my Class Code ...
Private Sub StartListen()
Try
' Must listen on correct port- must be same as port client wants to connect on.
Const portNumber As Integer = 6000
Dim tcpListener As New TcpListener(portNumber)
tcpListener.Start()
' Console.WriteLine("Waiting for connection...")
RichTextBox1.Text = RichTextBox1.Text & "Waiting for Connection ...." & vbCrLf
'
'
' SOH <ID> STX <DATA> ETX <CKSUM> EOT
'
'
Top:
'Accept the pending client connection and return a TcpClient initialized for communication.
Dim tcpClient1 As TcpClient = tcpListener.AcceptTcpClient()
' Get the stream
Dim networkStream As NetworkStream = tcpClient1.GetStream()
' Read the stream into a byte array
Dim bytes(tcpClient1.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient1.ReceiveBufferSize))
' Return the data received from the client to the console.
Dim clientdata As String = ASCIIEncoding.Unicode.GetString(bytes)
RichTextBox1.Text = RichTextBox1.Text & clientdata
Dim soh As String = GetChar(clientdata, 1)
Dim id As String = "010000000000000000"
Dim stx As String = GetChar(clientdata, 20)
Dim etx As String = GetChar(clientdata, 44)
Dim ack As String = System.Convert.ToChar(System.Convert.ToUInt32("06", 16))
Dim cksum As String = clientdata.Substring(44, 4)
Dim eot As String = GetChar(clientdata, 49)
Dim data As String = " 1Some Date "
Dim responseString As String = soh & id & stx & data & etx & cksum & eot & ack
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
RichTextBox1.Text = RichTextBox1.Text & vbCrLf & responseString & vbCrLf
tcpClient1.Close()
tcpListener.Stop()
GoTo Top
Catch e As Exception
Console.WriteLine(e.ToString())
Console.ReadLine()
End Try
End Sub
ASCIIEncoding.Unicode you should investigate that expression... This is equivalent to Encoding.Unicode which is not what you want (you want ASCII).
Also, you are ignoring the return value from Read which is a common mistake.

VB .net : How can a Server handle multiple clients simultaneosly at an instance

I am facing a problem in VB .net Client/Server application where I am successfully able to talk between them using TCPListener and TCPClient class usage. However, when I try to connect another Client to the same server on the same welcome port, it errors out throwing an exception or behaves very unexpectedly.
Isn't it true that the Server connection is on a WELCOME PORT for all the clients, and that each client connected gets a new port to carry on its communication with the server AUTOMATICALLY (according to the Tomcat webserver working)?
OR, is the above statement untrue and that the APP program handle the connections manually?
Pls clarify with an example in VB .net, if possible?
The answer to your question is 'Yes it is true'. I do not have VB.NET code ready but you can have a look at C# code here C# sockets handling multiple clients.
Okay.. pasting my server code here for your comments... Pls pardon my ignorance in coding and teach me if I were wrong. Thanks.
The Client is more obvious... so dint paste it here.
Server:
Public Class ServerSide2
...other stuff...
Public Class Packet
Public packetType As String = "Data"
Public packetOwnerIPAddress As String
Public packetOwnerPort As String
Public content As String
Public Sub New(ByVal type As String, ByVal ip As String, ByVal port As String, ByVal data As String)
packetType = type
packetOwnerIPAddress = ip
packetOwnerPort = port
content = data
End Sub
End Class
Public Class Worker
Dim myLogger As Logger
Dim name As String
Dim ipClientAddress As IPAddress 'Client's IP address
Dim ipClientPort As Integer = 22222 'Client listening on this port
Dim tcpServer As TcpListener
Dim tcpClient As TcpClient
Dim networkStream As NetworkStream
Dim readSize As Integer = 100
Public Sub New(ByRef logger As Logger, ByVal id As String)
myLogger = logger
name = id
myLogger.Trace("A new Worker object has been created for client: {0}", ipClientAddress)
End Sub
'Listener code
Public Sub runClientHandler(ByVal ar As IAsyncResult)
'code to listen to independent client
Dim clientdata As String
Dim numBytesRead As Integer = 0
Thread.CurrentThread.Priority = ThreadPriority.Highest
' Get the listener that handles the client request.
Dim listener As TcpListener = CType(ar.AsyncState, TcpListener)
' End the operation and display the received data on
' the console.
tcpClient = listener.EndAcceptTcpClient(ar)
' Process the connection here. (Add the client to a
' server table, read data, etc.)
myLogger.Info("Client connected completed")
' Signal the calling thread to continue.
tcpClientConnected.Set()
networkStream = tcpClient.GetStream()
Dim ipEndPoint As IPEndPoint = tcpClient.Client.RemoteEndPoint
ipClientAddress = ipEndPoint.Address
myLogger.Info("A new Worker thread has been started.")
While Not stopping
myLogger.Trace("Start looping.")
Dim bytes(readSize) As Byte
numBytesRead = networkStream.Read(bytes, 0, bytes.Length)
clientdata = Encoding.ASCII.GetString(bytes, 0, numBytesRead)
'check for validity of the data
If numBytesRead = 0 Then
'connection lost
myLogger.Trace("No data read.")
Exit While
End If
If clientdata.Contains("SampleTest : {") Then
'Message box the client data
MsgBox("Test data from Client = " + clientdata)
myLogger.Trace("Test data from Client = " + clientdata)
ElseIf clientdata.Contains("Recieve Port : ") Then
'Heed to Client's request on the port number server should reply
Dim dest(5) As Char
Dim destString As String = ""
clientdata.CopyTo(15, dest, 0, clientdata.Length - 15)
ipClientPort = CInt(CStr(dest))
myLogger.Trace("Client Waiting on Port# : " + CStr(dest) + "for sorted packets.")
'MsgBox("Client Waiting on Port# : " + CStr(dest))
ElseIf clientdata.Contains("Packet Size : ") Then
Dim dest(5) As Char
Dim destString As String = ""
clientdata.CopyTo(14, dest, 0, clientdata.Length - 14)
readSize = CInt(CStr(dest))
myLogger.Trace("Client's communicated Packet Size : " + CStr(dest))
Else
myLogger.Info("Begin to queue Data Packets.")
While True
myLogger.Info("Data Packet.")
SyncLock Stats.locker
myLogger.Info("Got the lock.")
Stats.queueLength = Stats.requestQueue.Count
If Stats.queueLength < Stats.MAX_QUEUE_LENGTH Then
'Queue has some space to fit more packets
myLogger.Info("Queue has some space for this packet.")
Stats.packetNum = Stats.packetNum + 1
Dim newPacket As Packet = New Packet("Data", ipClientAddress.ToString, ipClientPort, clientdata)
Stats.requestQueue.Enqueue(newPacket)
Stats.sumQueueLength = Stats.sumQueueLength + Stats.requestQueue.Count
Stats.meanQueueLength = Stats.sumQueueLength / Stats.packetNum
myLogger.Info("Stats :: Packet #: {0}, QueueLength: {1}, MeanQueueLength: {2}.", Stats.packetNum, Stats.requestQueue.Count, Stats.meanQueueLength)
Else
'Queue is FULL, Ignore the packet
Stats.numDropPackets = Stats.numDropPackets + 1
myLogger.Info("Stats :: Dropped Packets: {0}.", Stats.numDropPackets)
End If
End SyncLock
numBytesRead = networkStream.Read(bytes, 0, bytes.Length)
clientdata = Encoding.ASCII.GetString(bytes, 0, numBytesRead)
'check for validity of the data
If numBytesRead = 0 Then
'connection lost
myLogger.Trace("No data read.")
Exit Sub
End If
End While
End If
End While
myLogger.Trace("End looping.")
End Sub
End Class
Sub ListeningThread()
Dim count As Integer = 0
tcpServer = New TcpListener(ipAddress, iPort)
tcpServer.Start()
Try
While Not stopping And count < Stats.MAX_CLIENTS
count = count + 1
Dim workerName = "worker:" + CStr(count)
Dim worker As Worker = New Worker(logger, workerName)
logger.Info("Waiting for a client to connect")
DoBeginAcceptTcpClient(worker, tcpServer)
logger.Info("Connected to {0}.", workerName)
'Add the client to the hashTable
'ADITYA later clients.Add(workerName, client)
If SortAndSendThrd Is Nothing Then
'Start a new thread
SortAndSendThrd = New Thread(SortAndSendThrdStart)
SortAndSendThrd.Priority = ThreadPriority.Highest
End If
If Not SortAndSendThrd.IsAlive Then
SortAndSendThrd.Start()
logger.Debug("Started off a Sort thread")
End If
'Dim i As Integer = 0
'Dim objValue As Object
'For Each objKey In clients.Keys
' objValue = clients.Item(objKey)
' 'MsgBox("[" & objKey.ToString & ", " & objValue.ToString & "]")
'Next objKey
End While
Catch ex As IOException
ToolStripStatusLabel1.Text = "ERROR : SocketException: {0}" + ex.Message
'MsgBox(ex.Message + ":::2")
Catch ex As SocketException
ToolStripStatusLabel1.Text = "ERROR : SocketException: {0}" + ex.Message
'MsgBox(ex.Message + ":::1")
End Try
'tcpServer.Stop()
'client.Close()
logger.Debug("The Server's listening handler has come to an end.")
End Sub
End Class
When I try to connect a second client to this, the server drops the connection 1 and behaves unpredictably.