我需要将从网络流中读取的数据的第一个字节存储为字符串,以便稍后再调用它。
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");
这是我的服务器^一切正常,但我需要存储第一段数据,例如,如果我得到“名称”,它应该存储在一个数组中
由于
答案 0 :(得分:1)
您需要准确定义“第一条数据”的含义 - 这些数据是否以某种形式分隔(如HTTP标头 - 键/值对是否由回车换行符分隔)?长度前缀(如指定Content-Length标头时的HTTP主体)?你几乎肯定不只是想要第一个字节。
如果您希望只是发送名称然后发送其他内容,而没有任何迹象表明它们是不同的数据,那么您将会感到失望。流只是字节序列 - 没有(内置)说“读取客户端在第一次API调用中发送的内容”。
答案 1 :(得分:0)
这应该有效:
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