C # (Socket) asynchronous Socket code example

Source: Internet
Author: User

Asynchronous client socket example

The following example creates a client to connect to the server. The client is generated using an asynchronous socket, so the execution of the client application is not suspended when the server returns a response. The application sends the string to the server and then displays the string returned by the server on the console.

C #

Using System;
Using System. Net;
Using System. Net. Sockets;
Using System. Threading;
Using System. Text;
// State object for processing ing 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 = String. Empty;
Private static void StartClient (){
// Connect to a remote device.
Try {
// Establish the remote endpoint for the socket.
// The name of
// Remote device is "host.contoso.com ".
IPHostEntry ipHostInfo = Dns. Resolve ("host.contoso.com ");
IPAddress ipAddress = ipHostInfo. AddressList [0];
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.
Console. WriteLine ("Response received ed: {0}", response );
// Release the socket.
Client. Shutdown (SocketShutdown. Both );
Client. Close ();
} Catch (Exception e ){
Console. WriteLine (e. ToString ());
}
}
Private static 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 ());
// Signal that the connection has been made.
ConnectDone. Set ();
} Catch (Exception e ){
Console. WriteLine (e. ToString ());
}
}
Private static void Receive (Socket client ){
Try {
// Create the state object.
StateObject state = new StateObject ();
State. workSocket = client;
// Begin grouping ing the data from the remote device.
Client. BeginReceive (state. buffer, 0, StateObject. BufferSize, 0,
New AsyncCallback (effececallback), state );
} Catch (Exception e ){
Console. WriteLine (e. ToString ());
}
}
Private static void extends ecallback (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 stored Ed 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 (effececallback), 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 encoded ed.
ReceiveDone. Set ();
}
} Catch (Exception e ){
Console. WriteLine (e. ToString ());
}
}
Private static 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 static 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 );
// Signal that all bytes have been sent.
SendDone. Set ();
} Catch (Exception e ){
Console. WriteLine (e. ToString ());
}
}
Public static int Main (String [] args ){
StartClient ();
Return 0;
}
}
Asynchronous Server socket example the following sample program creates a server that receives connection requests from the client. This server is generated using an asynchronous socket,
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,
Display the string on the console and then display it back to the client. The string from the client must contain the string "<EOF> ",
The signal that indicates the end of the message.

C #
Copy code

Using System;
Using System. Net;
Using System. Net. Sockets;
Using System. Text;
Using System. Threading;
// 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 [1, 1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// Running the listener is "host.contoso.com ".
IPHostEntry ipHostInfo = Dns. Resolve (Dns. GetHostName ());
IPAddress ipAddress = ipHostInfo. AddressList [0];
IPEndPoint localEndPoint = new IPEndPoint (ipAddress, 11000 );
// Create a TCP/IP socket.
Socket listener = new Socket (AddressFamily. InterNetwork,
SocketType. Stream, ProtocolType. Tcp );
// Bind the socket to the local endpoint and listen for incoming connections.
Try {
Listener. Bind (localEndPoint );
Listener. Listen (100 );
While (true ){
// Set the event to nonsignaled state.
AllDone. Reset ();
// Start an asynchronous socket to listen for connections.
Console. WriteLine ("Waiting for a connection ...");
Listener. BeginAccept (
New AsyncCallback (AcceptCallback ),
Listener );
// Wait until a connection is made before continuing.
AllDone. WaitOne ();
}
} Catch (Exception e ){
Console. WriteLine (e. ToString ());
}
Console. WriteLine ("\ nPress ENTER to continue ...");
Console. Read ();
}
Public static void AcceptCallback (IAsyncResult ar ){
// Signal the main thread to continue.
AllDone. Set ();
// Get the socket that handles the client request.
Socket listener = (Socket) ar. AsyncState;
Socket handler = listener. EndAccept (ar );
// Create the state object.
StateObject state = new StateObject ();
State. workSocket = handler;
Handler. BeginReceive (state. buffer, 0, StateObject. BufferSize, 0,
New AsyncCallback (ReadCallback), state );
}
Public static void ReadCallback (IAsyncResult ar ){
String content = String. Empty;
// Retrieve the state object and the handler socket
// From the asynchronous state object.
StateObject state = (StateObject) ar. AsyncState;
Socket handler = state. workSocket;
// Read data from the client socket.
Int bytesRead = handler. EndReceive (ar );
If (bytesRead> 0 ){
// There might be more data, so store the data stored Ed so far.
State. sb. Append (Encoding. ASCII. GetString (
State. buffer, 0, bytesRead ));
// Check for end-of-file tag. If it is not there, read
// More data.
Content = state. sb. ToString ();
If (content. IndexOf ("<EOF>")>-1 ){
// All the data has been read from
// Client. Display it on the console.
Console. WriteLine ("Read {0} bytes from socket. \ n Data: {1 }",
Content. Length, content );
// Echo the data back to the client.
Send (handler, content );
} Else {
// Not all data has ed. Get more.
Handler. BeginReceive (state. buffer, 0, StateObject. BufferSize, 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 = Encoding. ASCII. GetBytes (data );
// Begin sending the data to the remote device.
Handler. BeginSend (byteData, 0, byteData. Length, 0,
New AsyncCallback (SendCallback), handler );
}
Private static void SendCallback (IAsyncResult ar ){
Try {
// Retrieve the socket from the state object.
Socket handler = (Socket) ar. AsyncState;
// Complete sending the data to the remote device.
Int bytesSent = handler. EndSend (ar );
Console. WriteLine ("Sent {0} bytes to client.", bytesSent );
Handler. Shutdown (SocketShutdown. Both );
Handler. Close ();
} Catch (Exception e ){
Console. WriteLine (e. ToString ());
}
}
Public static int Main (String [] args ){
StartListening ();
Return 0;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.