Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / Visual Basic
Tip/Trick

TcpClient.BeginConnect with Timeout

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
7 Oct 2014CPOL 17.6K   3  
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)


Written By
Software Developer
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --