【问题标题】:VB.NET: TCP Client Socket timeout?VB.NET:TCP 客户端套接字超时?
【发布时间】:2017-06-01 13:10:22
【问题描述】:

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

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

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

这是用于创建连接的 My Sub:

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

【问题讨论】:

  • 有一种内置的方式来做 Lars 的回答所暗示的事情。您可以使用BeginConnect 方法异步执行连接。显示完整使用情况here
  • @ProGrammer 我查看了您发送的链接,但我不确定如何修改我的代码以使用它?

标签: vb.net sockets tcp connection timeout


【解决方案1】:

您可以线程化整个CreateTCPConnection函数,然后在主线程中使用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

这是一个小的解决方法。

【讨论】:

    猜你喜欢
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    相关资源
    最近更新 更多