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

时间:2017-01-17 12:50:32

标签: vb.net sockets tcp connection timeout

我有一个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

1 个答案:

答案 0 :(得分:0)

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

这是一个小解决方法。