Sai Barker
Sai Barker

Reputation: 83

VB.NET: TCP Client Socket timeout?

I have a TCP Client socket that connects to a server when Form1 loads. I need a way for the client socket to "give up" trying to connect to the remote server if it takes too long to connect. i.e Time out after 30 seconds.

Currently when the socket cannot connect to the server for what ever reason the form will appear to freeze up until the server can be reached.

Its probably worth noting im using System.Net.Sockets.TcpClient()

Here is My Sub for creating the connection:

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

Upvotes: 2

Views: 5323

Answers (1)

Lars Crown
Lars Crown

Reputation: 226

You could thread the whole CreateTCPConnectionfunction, then you use a Timer in the Mainthread to abort the thread after X Seconds, if a public boolean is not setted to true.

Pseudo Code for the thread initialization:

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

This is a small workaround.

Upvotes: 1

Related Questions