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 8717453
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T06:18:33+00:00 2026-06-13T06:18:33+00:00

I am studying the MSDN example code of using asynchronous client-server sockets. I understand

  • 0

I am studying the MSDN example code of using asynchronous client-server sockets. I understand how this goes when new connection of client is made.

But how in case when client is already connected, and wants to pass some new data to the server (or to other clients)?

This is what I have so far:

public partial class Form1 : Form
{
    AsynchronousClient ac;
    public Form1()
    {
        InitializeComponent();            
    }

    private void buttonLogin_Click(object sender, EventArgs e)
    {
        buttonLogin.Enabled = false;
        new Thread(new ThreadStart(CreatingConnection)).Start();
    }

    private void CreatingConnection()
    {
        ac = new AsynchronousClient();
        ac.SendingMessage += (msg) => AC_SendingMassage(msg);
        ac.StartClient();
    }

    private void AC_SendingMassage(string message)
    {
        listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(message); });
    }

    private void buttonData_Click(object sender, EventArgs e)
    {
        string message = textBox1.Text;
        //TODO:
        //how to send data from here (including whats in textBox)??
    }
}

And this is the code (2 classes) from msdn`s example (incluidng only for client):

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 256;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient
{
    public event Action<string> SendingMessage;
    // The port number for the remote device.
    private const int port = 11000;

    // ManualResetEvent instances signal completion.
    private static ManualResetEvent connectDone = new ManualResetEvent(false);
    private static ManualResetEvent sendDone = new ManualResetEvent(false);
    private static ManualResetEvent receiveDone = new ManualResetEvent(false);

    // The response from the remote device.
    private string response;

    public void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            string ip = "192.168.1.101";
            IPAddress ipAddress = IPAddress.Parse(ip);
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            // Send test data to the remote device.
            Send(client, "This is a test<EOF>");
            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(client);
            receiveDone.WaitOne();

            // Write the response to the console.
            SendingMessage(string.Format("Response received : {0}", response));

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
        catch (Exception e)
        {
            SendingMessage(e.Message);
        }
    }

    private void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete the connection.
            client.EndConnect(ar);

            //Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());
            SendingMessage(string.Format("Socket connected to {0}", client.RemoteEndPoint.ToString()));

            // Signal that the connection has been made.
            connectDone.Set();
        }
        catch (Exception e)
        {
            //Console.WriteLine(e.ToString());
            SendingMessage(e.Message);
        }
    }

    private void Receive(Socket client)
    {
        try
        {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            SendingMessage(e.Message);
        }
    }

    private void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the state object and the client socket from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                // Get the rest of the data.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
            }
            else
            {
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1)
                {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            SendingMessage(e.Message);
        }
    }

    public void Send(Socket client, string data)
    {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
    }

    private void SendCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = client.EndSend(ar);
            //Console.WriteLine("Sent {0} bytes to server.", bytesSent);
            SendingMessage(string.Format("Sent {0} bytes to server.", bytesSent));
            // Signal that all bytes have been sent.
            sendDone.Set();
        }
        catch (Exception e)
        {
            SendingMessage(e.Message);
        }
    }
}

—
Up there is a click event of buttonData, which one I wanna use for passing data to server.
I would like to know which method to call to pass new data when already connected.

  • 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-13T06:18:34+00:00Added an answer on June 13, 2026 at 6:18 am

    You would send data using the Send method. However, this sample code looks like it was really just meant to show you how some of these asynchronous methods work. The StartClient method closes everything out, which is probably not what you would want to do. You will likely need to write your own code to do this.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I was studying the MSDN examples of using named pipes: Named pipe server using
I am studying 'Web Service' this week and found good tutorial and example code.
Studying asp.net mvc 3 + EF code-first. I am new to both. My example
Im studying some ruby code and I see this varx variable being used with
I am new to studying jquery.ajax. Through some tutorials, I tried some code by
I'm begginer with studying C++ using Xcode. I'm familiar with MSDN for Windows. Is
When studying a snippet of unknown Python code, I occasionally bump into the varName.methodName()
While studying for the SCJP 6 exam, I ran into this question in a
Im studying C# and came across a piece of code that Im quite confused
I am studying .net Remoting I've read from MSDN, but in one step I

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.