关于TCP客户端接收数据格式乱码,是一个485串口服务器网关连接电脑,485接线到电表读取用电量
发送 01 04 00 00 00 02 71 CB 接收到的是乱码
这是处理发送的代码
Sub SendMsg(ByVal Msg As String) '发送数据
Dim sendData As String = TxtSendMsg.Text
Try '捕获异常
sendData.Replace("0x", "")
sendData.Replace("0x", "")
Dim strArray() As String = sendData.Split(New Char() {",", ",", "\r", "\n", " ", "\t"})
Dim decnum As Integer = 0
Dim i As Integer = 0
Dim sendBuffer() As Byte = New Byte(strArray.Length) {}
Dim str As String
For Each str In strArray
Try
decnum = Convert.ToInt16(str, 16)
sendBuffer(i) = Convert.ToByte(decnum)
i = i + 1
Catch
End Try
Next
SockClient.Send(sendBuffer)
Catch ss As SocketException
ShowMsg(ss.Message)
Return
Catch s As Exception
ShowMsg(s.Message)
Return
End Try
ShowMsg("发送:" & Msg)
End Sub
这是接收的代码
Sub RecMsg() '接受数据处理
Dim buffMsgRec() As Byte = New Byte(1024 * 1024 * 10) {}
Dim length As Integer = -1
While True
Try '捕获异常
length = SockClient.Receive(buffMsgRec)
Catch ss As SocketException
ShowMsg(ss.Message)
Return
Catch s As Exception
ShowMsg(s.Message)
Return
End Try
Dim StrMsg As String
StrMsg = System.Text.Encoding.UTF8.GetChars(buffMsgRec, 0, length)
ShowMsg("接收:" & StrMsg)
End While
End Sub