Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

TcpClient.BeginConnect with Timeout

0.00/5 (No votes)
7 Oct 2014CPOL 18K  
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:

VB.NET
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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)