TCPClient / Server - 如何通过TCP / IP ASCII特殊字符发送数据

时间:2015-02-25 12:54:31

标签: vb.net ascii tcpclient tcplistener

我有一个应用程序,它当前通过TCP / IP端口6000发送请求,并等待回复。

我收到了请求/回复协议,但似乎无法发送ASCII控制字符,如SOH,SOT,EOT等... 01,02,03。

这是我通过TCP端口6000收到的,我可以在Msgbox中显示。 Enquiry Message http://www.hcs-it.com/Enquiry.jpg 这就是我要寄回去的...... Enquiry Message http://www.hcs-it.com/Response.jpg

这是我的班级代码......

Private Sub StartListen()
    Try
        ' Must listen on correct port- must be same as port client wants to connect on.
        Const portNumber As Integer = 6000
        Dim tcpListener As New TcpListener(portNumber)
        tcpListener.Start()
        ' Console.WriteLine("Waiting for connection...")
        RichTextBox1.Text = RichTextBox1.Text & "Waiting for Connection ...." & vbCrLf

        '
        '
        '    SOH <ID> STX <DATA> ETX <CKSUM> EOT
        '
        '
Top:

        'Accept the pending client connection and return a TcpClient initialized for communication. 
        Dim tcpClient1 As TcpClient = tcpListener.AcceptTcpClient()

        ' Get the stream
        Dim networkStream As NetworkStream = tcpClient1.GetStream()
        ' Read the stream into a byte array
        Dim bytes(tcpClient1.ReceiveBufferSize) As Byte
        networkStream.Read(bytes, 0, CInt(tcpClient1.ReceiveBufferSize))
        ' Return the data received from the client to the console.
        Dim clientdata As String = ASCIIEncoding.Unicode.GetString(bytes)

        RichTextBox1.Text = RichTextBox1.Text & clientdata

        Dim soh As String = GetChar(clientdata, 1)
        Dim id As String = "010000000000000000"
        Dim stx As String = GetChar(clientdata, 20)
        Dim etx As String = GetChar(clientdata, 44)

        Dim ack As String = System.Convert.ToChar(System.Convert.ToUInt32("06", 16))

        Dim cksum As String = clientdata.Substring(44, 4)
        Dim eot As String = GetChar(clientdata, 49)

        Dim data As String = " 1Some Date        "
        Dim responseString As String = soh & id & stx & data & etx & cksum & eot & ack
        Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
        networkStream.Write(sendBytes, 0, sendBytes.Length)

        RichTextBox1.Text = RichTextBox1.Text & vbCrLf & responseString & vbCrLf

        tcpClient1.Close()
        tcpListener.Stop()

        GoTo Top

    Catch e As Exception
        Console.WriteLine(e.ToString())
        Console.ReadLine()
    End Try


End Sub

1 个答案:

答案 0 :(得分:0)

ASCIIEncoding.Unicode您应该调查该表达式......这相当于Encoding.Unicode,这不是您想要的(您想要ASCII)。

此外,您忽略了Read的返回值,这是一个常见的错误。