SoFunction
Updated on 2025-03-07

c# (Socket) asynchronous socket code example

Asynchronous client socket example


The following example program creates a client that connects to the server. The client is generated with an asynchronous socket, so the execution of the client application is not suspended while waiting for the server to return a response. The application sends the string to the server and then displays the string returned by the server in the console.

C#

using System;
using ;
using ;
using ;
using ;
// State object for receiving data from remote device.
public class StateObject {
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousClient {
// 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 static String response = ;
private static void StartClient() {
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// The name of the 
// remote device is "".
IPHostEntry ipHostInfo = ("");
IPAddress ipAddress = [0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket(,
, );
// Connect to the remote endpoint.
( remoteEP,
new AsyncCallback(ConnectCallback), client);
();
// Send test data to the remote device.
Send(client,"This is a test<EOF>");
();
// Receive the response from the remote device.
Receive(client);
();
// Write the response to the console.
("Response received : {0}", response);
// Release the socket.
();
();
} catch (Exception e) {
(());
}
}
private static void ConnectCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket client = (Socket) ;
// Complete the connection.
(ar);
("Socket connected to {0}",
());
// Signal that the connection has been made.
();
} catch (Exception e) {
(());
}
}
private static void Receive(Socket client) {
try {
// Create the state object.
StateObject state = new StateObject();
 = client;
// Begin receiving the data from the remote device.
( , 0, , 0,
new AsyncCallback(ReceiveCallback), state);
} catch (Exception e) {
(());
}
}
private static void ReceiveCallback( IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket 
// from the asynchronous state object.
StateObject state = (StateObject) ;
Socket client = ;
// Read data from the remote device.
int bytesRead = (ar);
if (bytesRead > 0) {
// There might be more data, so store the data received so far.
((,0,bytesRead));
// Get the rest of the data.
(,0,,0,
new AsyncCallback(ReceiveCallback), state);
} else {
// All the data has arrived; put it in response.
if ( > 1) {
response = ();
}
// Signal that all bytes have been received.
();
}
} catch (Exception e) {
(());
}
}
private static void Send(Socket client, String data) {
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = (data);
// Begin sending the data to the remote device.
(byteData, 0, , 0,
new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket client = (Socket) ;
// Complete sending the data to the remote device.
int bytesSent = (ar);
("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
();
} catch (Exception e) {
(());
}
}
public static int Main(String[] args) {
StartClient();
return 0;
}
}
Asynchronous Server Socket Example The following example program creates a server that receives connection requests from the client. The server is generated using asynchronous sockets.
Therefore, the execution of the server application is not suspended while waiting for a connection from the client. The application receives strings from the client,
The string is displayed on the console and then echoes the string to the client. The string from the client must contain the string "<EOF>",
Send a signal indicating the end of the message.



 




C#
Copy the code

using System;
using ;
using ;
using ;
using ;
// State object for reading client data asynchronously
public class StateObject {
// Client  socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener {
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener() {
}
public static void StartListening() {
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "".
IPHostEntry ipHostInfo = (());
IPAddress ipAddress = [0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(,
,  );
// Bind the socket to the local endpoint and listen for incoming connections.
try {
(localEndPoint);
(100);
while (true) {
// Set the event to nonsignaled state.
();
// Start an asynchronous socket to listen for connections.
("Waiting for a connection...");
(
new AsyncCallback(AcceptCallback),
listener );
// Wait until a connection is made before continuing.
();
}
} catch (Exception e) {
(());
}
("\nPress ENTER to continue...");
();
}
public static void AcceptCallback(IAsyncResult ar) {
// Signal the main thread to continue.
();
// Get the socket that handles the client request.
Socket listener = (Socket) ;
Socket handler = (ar);
// Create the state object.
StateObject state = new StateObject();
 = handler;
( , 0, , 0,
new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar) {
String content = ;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject) ;
Socket handler = ;
// Read data from the client socket. 
int bytesRead = (ar);
if (bytesRead > 0) {
// There  might be more data, so store the data received so far.
((
,0,bytesRead));
// Check for end-of-file tag. If it is not there, read 
// more data.
content = ();
if (("<EOF>") > -1) {
// All the data has been read from the 
// client. Display it on the console.
("Read {0} bytes from socket. \n Data : {1}",
, content );
// Echo the data back to the client.
Send(handler, content);
} else {
// Not all data received. Get more.
(, 0, , 0,
new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data) {
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = (data);
// Begin sending the data to the remote device.
(byteData, 0, , 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket handler = (Socket) ;
// Complete sending the data to the remote device.
int bytesSent = (ar);
("Sent {0} bytes to client.", bytesSent);
();
();
} catch (Exception e) {
(());
}
}
public static int Main(String[] args) {
StartListening();
return 0;
}
}