storing first byte as string from network stream - vb.net

I need to store the first byte of data read from the network stream as a string, so I can call it back later.
prinf(" While 1
Dim tcpListener As New TcpListener(IPAddress.Any, 80) ' Listen to port given
Console.WriteLine("Waiting for connection...")
tcpListener.Start()
'Accept the pending client connection and return 'a TcpClient initialized for communication.
Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
Console.WriteLine("Connection accepted.")
' Get the stream
Dim networkStream As NetworkStream = tcpClient.GetStream()
' Read the stream into a byte array
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
' Return the data received from the client to the console.
Dim clientdata As String = Encoding.ASCII.GetString(bytes)
Console.WriteLine(("Client Sent: " + clientdata))
' Return the data received from the client to the console.
Dim responseString As String = "Hello"
'Dim chat_name As String = "Name"
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
Console.WriteLine(("Response: " + responseString))
tcpClient.Close() 'Close TcpListener and TcpClient
tcpListener.Stop()
End While");
Thats my server ^ everything works fine, but I need the 1st piece of data read to be stored, such as if I get "Name" it should be stored in an array
Thanks

You'll need to define exactly what you mean by "1st piece of data" - is this data delimited in some form (like HTTP headers - key/value pairs are delimited by carriage-return line-feed)? Length-prefixed (like HTTP bodies when the Content-Length header is specified)? You almost certainly don't just want the first byte.
If you were hoping to just send the name and then send something else, without any indication of the fact that they're different bits of data, you're going to be disappointed. Streams are just sequences of bytes - there's nothing (built-in) to say "read what the client sent in their first API call".

This should work:
Dim strFirstByte as string = vbNullString
While 1
' ... Your code ...
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
If strFirstByte = vbNullString Then strFirstByte = bytes(0).ToString("X2")
' ... The rest of your code ...
End While

Related

Simple TCP Client Program for Send Hex Bytes using VB.Net 2015

I tried to send Hex bytes through the TCP using VB.net. And receive the response of data.
Following code I used,
Dim tcpClient As New System.Net.Sockets.TcpClient()
tcpClient.Connect("192.168.1.10", 502)
Dim networkStream As NetworkStream = tcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
' Do a simple write.
Dim sendBytes As [Byte]() = {&H0, &H4, &H0, &H0, &H0, &H6, &H5, &H3, &HB, &HD3, &H0, &H1}
networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
' Output the data received from the host to the console.
Dim returndata As String = Encoding.ASCII.GetString(bytes)
TextBox1.Text = ("Host returned: " + returndata)
Else
If Not networkStream.CanRead Then
TextBox1.Text = "cannot not write data to this stream"
tcpClient.Close()
Else
If Not networkStream.CanWrite Then
TextBox1.Text = "cannot read data from this stream"
tcpClient.Close()
End If
End If
End If
When I send sendbytes data, I did not get any data. When I send data, master automatically sends me data but I did not get any data. This is Modbus communication.
I can only see Host returned:
The data is there, but you cannot see it because it starts with a null byte (&H0 or just 0). Most text controls that encounter a null byte interprets that as the end of the string and thus doesn't render the rest of the text.
GetString() merely takes the bytes as is and converts them into the respective chars with the same values. It is up to you to turn the result into a readable format.
The solution is to skip GetString() and instead iterate the array, converting every byte into a hex or number string.
Also, two very important things:
You shouldn't use TcpClient.ReceiveBufferSize in your code as it is used for the internal buffer. You should always decide the buffer size on your own.
Since TCP is a stream-based protocol the application layer has no notion of packets. One 'send' from the server usually does not equal one 'receive'. You might receive more or less data than what the first packet actually is. Use the return value from NetworkStream.Read() to determine how much has been read.
You then need to read up on the Modbus documentation and see if its data contains something that indicates the end or the length of a packet.
'Custom buffer: 8 KB.
Dim bytes(8192 - 1) As Byte
Dim bytesRead As Integer = networkStream.Read(bytes, 0, bytes.Length)
Dim returndata As String = "{"
'Convert each byte into a hex string, separated by commas.
For x = 0 To bytesRead - 1
returnData &= "0x" & bytes(x).ToString("X2") & If(x < bytesRead - 1, ", ", "}")
Next
TextBox1.Text = "Host returned: " & returnData

Setting a TCP Client to receive broadcasted data

I am writing a program in VB.net that is connecting to a server, sending a byte array to the server and then receives a byte array as an answer then needs to receive a continuous stream of bits from the server.
The Sent Bit Array is 84 bytes and should be the same the first time it is received from the server and vary in size every time the server sends it back after that.
the start and the end of the message will always be the same but the size of the bit array sent will vary.
My issue is that I can write the bits to the server but I am not able to receive any of the follow-on bits that are broadcast.
Any suggestions
Public Sub connect(TcpClient As TcpClient)
Dim NetworkStream As NetworkStream = TcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
' Do a simple write.
Dim sendBytes As [Byte]() = IO.File.ReadAllBytes(startupFile)
networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.
Dim bytes(1024) As Byte
NetworkStream.Read(bytes, 0, bytes.Length)
' Output the data received from the host to the console.
Dim returndata As String = Encoding.ASCII.GetString(bytes)
Dim fileWrite As New IO.StreamWriter(writeFile)
fileWrite.Write(returndata)
fileWrite.Close()
Else
If Not networkStream.CanRead Then
Console.WriteLine("cannot not write data to this stream")
TcpClient.Close()
Else
If Not networkStream.CanWrite Then
Console.WriteLine("cannot read data from this stream")
TcpClient.Close()
End If
End If
End If
End Sub

Issue sending big string over TCP

I have the following function to send and receive data it works OK for short strings like 150 bytes, but with a string of 2500 bytes it get stuck.
I tried to send some data with HTWin and nothing get the other end of the net.
So receiver on the other end never get even a character.
I tried also with the old Hyperterminal with same result.
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
If I split the big string into smaller one and call this function over and over all the data reach the other end.
Also, I need to get an ACK packet that is big too and the code must wait for and special character that indicates the end.
I was thinking in to create a Thread with a TcpListener but, Is possible to have a TcpListener in the same port of a TcpClient?
The whole idea is to send a big string that is separated by an special character and finished with another special character.
The other end receive the data, split the string using the first special character and send one ACK by every item in the split function.
And in the last ACK send the second special character to indicate the end of the communication, so my application can process the received data properly.
I think I'm drowning in a glass of water.

Sending multiple hex in array of bytes instead

I have problem about socket to send multiple hex in one send to socket
Here the detail :
Private Sub sendACK()
Dim msgACK As String
Dim sendBytes As Byte()
tmpStr = ""
list.Clear()
msgACK = "33CC"
For j = 1 To Len(msgACK)
list.Add(Mid(msgACK, j, 2))
j += 1
Next
For Each tmpStr In list
sendBytes = HexToBytes(tmpStr)
clientSocket.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, New System.AsyncCallback(AddressOf OnSend), clientSocket)
Next
End Sub
Public Function HexToBytes(ByVal s As String) As Byte()
Dim bytes As String() = s.Split(" "c)
Dim retval(bytes.Length - 1) As Byte
For ix As Integer = 0 To bytes.Length - 1
retval(ix) = Byte.Parse(bytes(ix), System.Globalization.NumberStyles.HexNumber)
Next
Return retval
End Function
Private Sub OnSend(ByVal ar As IAsyncResult)
clientSocket = ar.AsyncState
clientSocket.EndSend(ar)
Thread.Sleep(100)
End Sub
==> List as arraylist
That code will be result :
Socket send 33
end send
Socket send CC
end send
============================
The program should be sending in one time like this :
Socket send 33 CC
end send
============================
is there any idea about convert string "33CC" into byte and then that program just sending 1 time in outter "for each" ?
thanks for reading and answering....
GBU
Your assumption is incorrect. It does indeed send both bytes at once. You are only calling BeginSend once and you are giving it both bytes, so if it is receiving them at all on the other end, then it is indeed sending them. In fact, there is no difference at all between sending them individually or sending them together. Since the socket works as a stream, the length of time between each byte being sent is largely irrelevant. There will be no way on the receiving end to know whether the two bytes were sent together or separately. All the receiving end will know is that the two bytes were sent in that order. If you think they are being sent as two separate "sends" on the receiving end, it sounds like you are making some invalid assumptions about how to read the data from the socket.
However, I should mention that the way you are sending the bytes, by first creating a hex string and then parsing it, is a bit silly. If you need to parse it as a string, because you are reading the hex values from a text file, or something, that's fine, but otherwise, you should just use hex byte literals in your code rather than strings, for instance:
Dim sendBytes As Byte() = {&H33, &HCC}

.NET Socket Send & Receive Not Matching

I have these following lines to send bytes using socket
Dim server As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim myIp As IPAddress = IPAddress.Parse("myIP")
Dim ip As New IPEndPoint(myIp, Int32.Parse("myPort"))
server.Connect(ip)
server.Send(Encoding.UTF8.GetBytes("Halo")
These are the lines I use to receive
Dim data(255) As Byte
Dim bytesReceived As Integer = socket.Receive(buffer)
Dim stringData As String = Encoding.UTF8.GetString(data)
My problem:
As in the code, I am supposed to retrieved "Halo". Instead I keep receiving sth like "[]". Can someone give me advise on this?
In order to receive data on a socket, you need to use the Socket.Receive method. Here's an example of what you need to do:
'Dim sock As Socket
Dim buffer(255) As Byte 'the data will be stored here
Dim bytesReceived As Integer = socket.Receive(buffer) 'will be used to see how many bytes were received
'not all bytes in the buffer contain data, so only use the number equal to the number received
Dim result As String = Encoding.UTF8.GetString(buffer, 0, bytesReceived)
I would recommend using a larger buffer, though, such as 4096.
http://msdn.microsoft.com/en-us/library/w89fhyex.aspx contains a few synchronous and asynchronous socket examples.