65.9K
CodeProject is changing. Read more.
Home

TcpClient.BeginConnect with Timeout

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Oct 7, 2014

CPOL
viewsIcon

18002

TcpClient.BeginConnect with timeout

Introduction

When we need to connect to hundreds or thousands of remote computers, we can try to use Parallel.ForEach. But it is the wrong way because it will take too many resources. Another mistake is to use "For (Each) ... Next" because it's too long.

While optimizing my code, I found a perfect solution which helped me to connect to more than 262144 remote IPs in an extremely short period of time. Check it out:

Imports System.Net.Sockets

Public Class toTcpClient
    Inherits TcpClient
    Public tmr As System.Threading.Timer
    Public id As String = ""
    Public Event TimeoutReached(ByVal sender As toTcpClient)
    Public Sub BeginConnectWithTimeout(ByVal host As String,
                                       ByVal port As Integer,
                                       ByVal ConnectCallback As System.AsyncCallback,
                                       Optional ByVal timeout As Integer = 100)
        BeginConnect(host, port, ConnectCallback, Me)
        tmr = New Threading.Timer(AddressOf toTcpClient_TimeoutReached, _
        	Nothing, timeout, System.Threading.Timeout.Infinite)
    End Sub

    Private Sub toTcpClient_TimeoutReached(ByVal e As Object)
        RaiseEvent TimeoutReached(Me)
    End Sub
End Class

Now you can create an effective procedure to connect through [For...Next]. So, if tcpClient connected successfully, first of all turn off Timer object using Dispose. Else, you should close tcpClient in TimerCallback.

Enjoy!