接收TCP / IP响应后Visual Basic窗体冻结(Visual Basic form fr

2019-09-26 20:16发布

我有一个基本的TCP / IP通信的Python之间的Linux主机和Visual Basic的Windows主机上安装。 Windows主机似乎很好地工作,作为一个测试,我送一个0到Linux机器,并把它印到Visual Basic调试控制台0回应。 所有工作正常,但Visual Basic中接收响应,并成功地显示它后,它冻结的形式,所以我不能按另一个按钮。 下面的代码示例。

Imports System.Net
Imports System.Net.Sockets
Imports System.Text

Public Class Form1
    Shared Sub Main()
        Dim tcpClient As New System.Net.Sockets.TcpClient()
        tcpClient.Connect("192.168.60.124", 9999)
        Dim networkStream As NetworkStream = tcpClient.GetStream()
        If networkStream.CanWrite And networkStream.CanRead Then
            ' Do a simple write.
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("0")
            networkStream.Write(sendBytes, 0, sendBytes.Length)
            ' Read the NetworkStream into a byte buffer.
            Dim bytes(tcpClient.ReceiveBufferSize) As Byte
            networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
            ' Output the data received from the host to the console.
            Dim returndata As String = Encoding.ASCII.GetString(bytes)
            Console.WriteLine(("Host returned: " + returndata))
            tcpClient.Close()
        Else
            If Not networkStream.CanRead Then
                Console.WriteLine("cannot not write data to this stream")
                tcpClient.Close()
            Else
                If Not networkStream.CanWrite Then
                    Console.WriteLine("cannot read data from this stream")
                    tcpClient.Close()
                End If
            End If
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Main()
    End Sub
End Class   

Answer 1:

由于OP的要求,我搬到了我的批评是对我的回答后部分^^

请参阅多线程和Console.WriteLine ,

“许多人使用Console.WriteLine这一在多线程程序的日志记录。但实际上,它会使事情慢。 控制台I / O流是同步的 ,也就是说,它是阻塞I / O操作 。当多个线程使用Console.WriteLine, 只一个线程可以执行I / O操作和其他需要等待 。”

我不知道这是为什么Console.WriteLine命令块的UI?


原贴

我想知道,你需要做的多线程编程使用Visual Basic .NET 。 因为你在你的主线程(UI线程)的TCP客户端活动。 因此,除非TCP客户端活动完成后,你不能做你的UI的内容,如按钮点击。

我的建议是把你的TCP客户端活动进入功能和启动另一个线程继续被点击您的按钮1之后。

Sub Tcpclient()
    ' The statement of TCPClient function
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim tcpClientThread As New System.Threading.Thread( _
        AddressOf Tcpclient)
    tcpClientThread.Start()
End Sub


文章来源: Visual Basic form freezes after receiving tcp/ip response