Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8365115
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T12:34:59+00:00 2026-06-09T12:34:59+00:00

ALL, I am using an Asynchronous socket in C#. My problem is: I want

  • 0

ALL,
I am using an Asynchronous socket in C#.
My problem is: I want to wait for a callback to finish with connection, because I need to immediately send the information to a server.

Here is a code snippet:

class InternetConnector
{
    private struct ConnectionData
    {
        public Action<Exception> ErrorHandler { get; set; }
        public Socket Socket { get; set; }
    }
    public void ConnectToHost(Action<Exception> errorHandler)
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Parse(connector_host), connector_port);
        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        var ConnectionData = new ConnectionData { ErrorHandler = errorHandler, Socket = client };
        client.Blocking = true;
        client.BeginConnect(ip, new AsyncCallback(ConnectCallback), ConnectionData);
        connectDone.WaitOne(100);
    }

    private static void ConnectCallback(IAsyncResult ar)
    {
        ConnectionData connectionData = new ConnectionData();
        try
        {
            connectionData = (ConnectionData)ar.AsyncState;
            connectionData.Socket.EndConnect(ar);
            connectDone.Set();
            Connected = true;
        }
        catch (Exception e)
        {
            if (connectionData.ErrorHandler != null)
                connectionData.ErrorHandler(e);
        }
    }
}

public partial class Form1 : Form
{
    private bool isRunning = false;
    private InternetConnector client = new InternetConnector();

    private void AsyncErrorHandler(Exception e)
    {
        if (status.InvokeRequired)
        {
            status.BeginInvoke(new Action(() => AsyncErrorHandler(e)));
            return;
        }
        InternetConnector.Connected = false;
        isRunning = false;
        startStop.Text = "Start";
        status.ForeColor = Color.Red;
        status.Text = "Socket Error: " + e.Message;
    }

    private void startStop_Click(object sender, EventArgs e)
    {
        if (!isRunning || !InternetConnector.Connected)
        {
            if (!InternetConnector.Connected)
            {
                client.SetAddress(ipAddress.Text);
                client.SetPort(Convert.ToInt32(connectionport.Text));
                client.ConnectToHost( AsyncErrorHandler );
                status.Text = "Signals Receiver: Connected";
                status.ForeColor = Color.Green;
                startStop.Text = "Stop";
                isRunning = true;
     // if connection successful, send some data and start reading the socket
            }
            else
            {
                startStop.Text = "Start";
                client.DisconnectFromHost(AsyncErrorHandler);
                isRunning = false;
            }
        }
    }
}

I can handle the exception in the connection. Now I need to handle the successful connection as well.

Thank you.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T12:35:00+00:00Added an answer on June 9, 2026 at 12:35 pm

    You can follow the same pattern, and supply a handler to be called on success as well as on error:

    class InternetConnector 
    { 
        private struct ConnectionData 
        { 
            public Action<Socket> SuccessHandler { get; set; } 
            public Action<Exception> ErrorHandler { get; set; } 
            public Socket Socket { get; set; } 
        } 
    
        public void ConnectToHost(Action<Socket> successHandler, Action<Exception> errorHandler) 
        { 
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse(connector_host), connector_port); 
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            var ConnectionData = new ConnectionData 
            { 
                SuccessHandler = successHandler,
                ErrorHandler = errorHandler, 
                Socket = client 
            }; 
            client.Blocking = true; 
            client.BeginConnect(ip, new AsyncCallback(ConnectCallback), connectionData); // <--  make sure to use the lower-case connectionData here!  :)
            connectDone.WaitOne(100); 
        } 
    
        private static void ConnectCallback(IAsyncResult ar) 
        { 
            ConnectionData connectionData = new ConnectionData(); 
            try 
            { 
                connectionData = (ConnectionData)ar.AsyncState; 
                connectionData.Socket.EndConnect(ar); 
                connectDone.Set(); 
                Connected = true; 
                if (connectionData.SuccessHandler != null)
                    connectionData.SuccessHandler(connectionData.Socket);
            } 
            catch (Exception e) 
            { 
                if (connectionData.ErrorHandler != null) 
                    connectionData.ErrorHandler(e); 
            } 
        } 
    } 
    

    The signature of the function you pass as a success handler must match the Action<Socket> delegate, which would look something like:

    void MySuccessHandler(Socket socket) 
    { 
        // do stuff with the connected socket..        
        Console.WriteLine("Connected to {0}", socket.RemoteEndPoint);         
    }
    
    void MyErrorHandler(Exception e)
    {
        Console.WriteLine("Connection error {0}", e.Message);         
    }
    
    ...
    
    myConnector.ConnectToHost(MySuccessHandler, MyErrorHandler);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm developing an Asynchronous Game Server using .Net Socket Asynchronous Model( BeginAccept/EndAccept...etc.) The problem
I need a way to remove ALL using statements from code and fully qualify
Hi all im using a sqlite helper class, but i have a little problem
When using asynchronous sockets, specifically, Socket.ReceiveAsync, is it possible to do a 'partial' receive?
I am using Asynchronous socket. the server sends MSG to client continuously. client receives
I want to read from a socket in an asynchronous way. If I used
Please note the question is about using an asynchronous callback mode only on sockets
I have written a TCP server using the Socket class's asynchronous/IOCP methods, BeginSend()/BeginRead()/etc. I
Once I run search all using Ctrl + Shift + F then my search
Possible Duplicate: Should Usings be inside or outside the namespace sa1200 All using directives

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.