VB.NET:TCP 客户端套接字超时



我有一个TCP客户端套接字,当Form1加载时连接到服务器。我需要一种方法让客户端套接字"放弃"尝试连接到远程服务器,如果连接时间太长。即 30 秒后超时。

目前,当套接字由于某种原因无法连接到服务器时,表单将显示为冻结,直到可以访问服务器。

可能值得注意的是,我使用System.Net.Sockets.TcpClient()

这是用于创建连接的我的子:

Public serverStream As NetworkStream
Public clientSocket As New System.Net.Sockets.TcpClient()    
Public Sub CreateTCPConnection()
    Try
        clientSocket.Connect(System.Net.IPAddress.Parse(My.Settings.ServerIP), My.Settings.ServerPort)
        ConnectionStatusLbl.Text = "Connection: Connected"
        ConnectionStatusPB.Image = My.Resources.LED_Green
        'This should work according to MSDN but does not
        clientSocket.SendTimeout = 3000
        clientSocket.ReceiveTimeout = 3000
        UpdateTimer.Start()
    Catch ex As Exception
        ConnectionStatusLbl.Text = "Connection: Not Connected"
        ConnectionStatusPB.Image = My.Resources.LED_Red
        clientSocket.Close()
        MsgBox(ex.ToString)
    End Try

End Sub

您可以线程化整个CreateTCPConnection函数,然后在 X 秒后使用Timer在 X 秒后中止线程,如果公共布尔值未设置为 true。

线程初始化的伪代码:

Dim isConnected as Boolean

Private Sub Form1_Load( _
   ByVal sender As System.Object, ByVal e As System.EventArgs) _
   Handles MyBase.Load
   isConnected = false;
   trd = New Thread(AddressOf CreateTCPConnection)
   trd.IsBackground = True
   //Afer the start function the thread tries to connect asyncron to your server
   trd.Start()
   Timer timer = new Timer();
   //Start the timer to check the boolean
   myTimer.Tick += new EventHandler(TimerEventProcessor);
   myTimer.Start()
End Sub
Private Sub CreateTCPConnection()
 //Your Connection method
End Sub
//Checks the isConnected status each second. If isConnected is false and 3 seconds are reached, the thread gets aborted.
Private Sub TimerEventProcessor(Object myObject,
                                        EventArgs myEventArgs) 
   if(myEventArgs.elapsedTime >= 3 AND isConnected == false) Then
      trd.Abort();
   End if
End Sub

这是一个小的解决方法。

相关内容

  • 没有找到相关文章

最新更新