Need Faster Socket.BeginRecieve and Socket.Send

Posted on 2005-04-09
Last Modified: 2008-01-09
My Question is, is there any way to make that send faster? Should I be using something different than a Socket if I want to go faster? by faster I mean, maximizing my internet connection....and the same with the BeginRecieve, can I somehow have the send and the recieve on seperate threads? would that increase download and upload rates?

Ok my Socket.Send is this

      Public Sub sendall(ByVal low As String, ByVal high As String, ByVal s As Socket)
            nlow = low
            dohed = True
            Dim g As String : Dim h() As Byte
            RaiseEvent Err(Date.Now)
            Do Until nlowcnt = 500
                g = "HEAD " & nlow & vbCrLf
                h = StringToBytes(g)
                s.Send(h, h.Length, 0)
                nlow += 1
                nlowcnt += 1
            RaiseEvent Err(Date.Now)
        End Sub

My BeginRecieve is this

     Private Sub sockDataArrival(ByVal ar As IAsyncResult)
            Dim state As StateObject = CType(ar.AsyncState, StateObject)
            Dim client As Socket = state.workSocket
            Dim bytesRead As Integer
                bytesRead = client.EndReceive(ar)
                Exit Sub
            End Try
                Dim Data() As Byte = state.buffer
                If bytesRead = 0 Then
                    RaiseEvent Err("ON DISCONNECT")
                    Exit Sub
                End If
                ReDim state.buffer(32767)
                client.BeginReceive(state.buffer, 0, state.BufferSize, SocketFlags.Peek, AddressOf sockDataArrival, state)

                ondataarrival(Data, bytesRead, client)
            Catch ex As Exception
                RaiseEvent Err(ex.ToString)
                Exit Sub
            End Try
        End Sub

Question by:addicktz
    1 Comment
    LVL 2

    Accepted Solution

    Here is a TCP socket controle that i made a wile back, it is using a multi thred aproach perhaps this will help, keep in mind that this a "CLIENT" side only and its also a library file not a executable.

    #Region " --Imports-- "
    Imports System.Net
    Imports System.Net.Sockets
    #End Region

    Public Class TCPIP_Socket
        Inherits System.Windows.Forms.UserControl

    #Region " Windows Form Designer generated code "

        Public Sub New()

            'This call is required by the Windows Form Designer.

            'Add any initialization after the InitializeComponent() call

        End Sub

        'UserControl1 overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                End If
            End If
        End Sub

        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer

        'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Friend WithEvents Label1 As System.Windows.Forms.Label
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.Label1 = New System.Windows.Forms.Label
            Me.Label1.Dock = System.Windows.Forms.DockStyle.Fill
            Me.Label1.Location = New System.Drawing.Point(0, 0)
            Me.Label1.Name = "Label1"
            Me.Label1.Size = New System.Drawing.Size(120, 32)
            Me.Label1.TabIndex = 0
            Me.Label1.Text = "TCP/IP Socket"
            Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
            Me.Name = "TCPIP_Socket"
            Me.Size = New System.Drawing.Size(120, 32)

        End Sub

    #End Region

    #Region " --Object Properties-- "
        Private ad As String = "Not Connected"
        Private lpt As String = "n/a"
        Private rpt As String = "n/a"

        Public Function getAddress() As String
            Return ad
        End Function
        Public Function getLocalPort() As String
            Return lpt
        End Function
        Public Function getRemotePort() As String
            Return rpt
        End Function
    #End Region

    #Region " --Connection/connection objects-- "
        Private ClientSocket As Socket
        Private ASCII As New System.Text.ASCIIEncoding
        Private Delegate Sub NoParamsDelegate()
        Private Delegate Sub OneStringDelegate(ByVal data As String)

        Public Sub Connect(ByVal srv As String, ByVal pt As String)
            '--Resolve IP address/Host Name
            Dim addr As IPAddress = Dns.Resolve(srv).AddressList(0)
            ad = srv
            lpt = pt
            rpt = pt
            If Not addr Is Nothing Then
                '--Create an IP endpoint
                Dim EP As New IPEndPoint(addr, CInt(pt))
                '--Create a new Socket
                ClientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                ClientSocket.BeginConnect(EP, AddressOf ConnectCallback, Nothing)
            End If
        End Sub

        Private Sub ConnectCallback(ByVal ar As IAsyncResult)
                Dim dlg As New NoParamsDelegate(AddressOf ConnectedUI)
                'Begin Recieving data
                Dim bytes(4095) As Byte
                ClientSocket.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, AddressOf ReceiveCallback, bytes)
                ad = "Not Connected"
                lpt = "n/a"
                rpt = "n/a"
                DisplayReceivedData(vbCrLf & "Connection not available on port " & lpt & vbCrLf)
            End Try
        End Sub

        Private Sub ReceiveCallback(ByVal ar As IAsyncResult)
            Dim bytes() As Byte = CType(ar.AsyncState, Byte())
            Dim numbyte As Int32 = ClientSocket.EndReceive(ar)
            If numbyte = 0 Then
                Dim dlg As New NoParamsDelegate(AddressOf DisconnectedUI)
                Dim Recv As String = ASCII.GetString(bytes, 0, numbyte)
                '--Clear Buffer
                Array.Clear(bytes, 0, bytes.Length)
                '--Show in UI
                Dim dlg As New OneStringDelegate(AddressOf DisplayReceivedData)
                Dim args() As Object = {Recv}
                Me.Invoke(dlg, args)
                '--Begin Reveiciving again
                ClientSocket.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, AddressOf ReceiveCallback, bytes)
            End If
        End Sub
    #End Region

    #Region " --Send Data-- "
        Public Sub SendString(ByVal data As String)
            Dim bytes() As Byte = ASCII.GetBytes(data)
        End Sub
    #End Region

    #Region " --Events-- "
        Event Connected()
        Event Disconnected()
        Event ReceiveData(ByVal e As String)

        Private Sub ConnectedUI()
            '--Rais Event Connected--'
            RaiseEvent Connected()
        End Sub

        Private Sub DisconnectedUI()
            ad = "Not Connected"
            lpt = "n/a"
            rpt = "n/a"
            '--Raise Event Disconnected--'
            RaiseEvent Disconnected()
        End Sub

        Private Sub DisplayReceivedData(ByVal data As String)
            '--Raise Event Receiving--'
            RaiseEvent ReceiveData(data)
        End Sub
    #End Region

    End Class

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
    Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
    Hi everyone! This is Experts Exchange customer support.  This quick video will show you how to change your primary email address.  If you have any questions, then please Write a Comment below!
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now