我的程序无法从TCP连接读取ASCII字符串,继续循环

时间:2018-06-08 13:55:40

标签: vb.net visual-studio tcp

我正在连接到服务器的特定TCP端口,执行操作,我需要在某些时候断开连接,然后等待服务器再次打开其端口并重新连接。

我的程序永远循环。

要断开与服务器的连接,我从服务器发送字符串“TCP:OFF”并关闭端口(服务器端)。每当我的程序读取此行时,我希望它关闭其连接并等待服务器再次打开其端口。这是因为TCP / IP协议。

问题是,在我将鼠标放在窗口上之前,我的服务器发送的特定ASCII字符串不会被读取(很奇怪)。最后,我希望我的程序能够独立工作并最小化,而无需人工干预。

我的networkStream阅读时间一定存在问题。

代码

While tcpClient.Connected() = False
        Try
            tcpClient.ReceiveTimeout = 1000
            tcpClient.SendTimeout = 1000
            tcpClient.Connect("192.168.10.100", 10003)
            Console.WriteLine("Connection OK")
            System.Threading.Thread.Sleep(1000)
        Catch ex As Exception
            Console.WriteLine("ERRORR : Server unreachable")
            System.Threading.Thread.Sleep(1000)
        End Try
    End While

Dim networkStream As NetworkStream = tcpClient.GetStream()

If networkStream.CanRead And networkStream.DataAvailable Then
        Try
            ReadData = ""
            Dim myReadBuffer As Byte() = New Byte(7) {}
            Dim numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length)
            ReadData = Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead)
            Console.Write(ReadData & vbCrLf)
        Catch ex As Exception
            Console.Write("Error reading data")
        End Try
    End If

    If ReadData = "TCP:OFF" Then
        tcpClient.Close()
        ReadData = ""
        Console.WriteLine("Closing connection")
        System.Threading.Thread.Sleep(5000)
        tcpClient = New TcpClient
    End If

我正在最新的Visual Studio中执行Windows窗体程序。

0 个答案:

没有答案