【发布时间】:2019-09-26 00:35:25
【问题描述】:
我是 vb.net 2008 的新手,使用 tcpclient() 从称重秤获取数据。下面提到的代码能够与机器连接但无法获取数据。但是超级终端可以获取数据。
我搜索了大部分帖子,但可能只存在用于串行端口连接的编码。
输出消息框: 收到:{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
【问题讨论】:
-
您的错误日志中有占位符 {0},如果您使用 MsgBox($"Received: {0} " & responseData)
-
我得到了空的响应数据作为输出。但机器状态已连接。但唯一的问题是没有接收到数据。
-
您需要为您的体重秤查找一些文档。无法保证数据以纯文本形式发送。它可能包含由字节序列(或两者)表示的控制字符或数字。
-
旁注:
{0}用作String.Format()等函数的占位符。您正在使用常规字符串连接,因此{0}成为字符串的一部分,而不是被替换为值。你应该把它从你的字符串中完全删除。 -
感谢@VisualVincent,我是 vb.net 的新手。我将与体重秤支持人员核实,我将更新控制字符。