Storing the first byte as a string from a network stream
I need to store the first byte of data read from the network stream as a string, so I can call 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");
Here is my server ^ everything works fine, but I need the 1st chunk of read data to be stored, for example if I get "Name" it should be stored in an array
thank
You will need to define exactly what you mean by "1st piece of data" - is this data limited in some form (eg HTTP headers - key / value pairs are delimited by a carriage return line / line)? Length-prefixed (like HTTP tags when Content-Length header is specified)? You almost certainly don't just want the first byte.
If you were hoping to just send a name and then send something else, without any indication that they are different bits of data, you will be disappointed. Streams are just sequences of bytes - there is nothing (built in) to say "read what the client sent in its first API call".
source to share
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
source to share