C # (socket) Asynchronous Socket code Sample _c# Tutorial

Source: Internet
Author: User
Tags string back
Asynchronous Client Socket Example


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

C#

Using System;
Using System.Net;
Using System.Net.Sockets;
Using System.Threading;
Using System.Text;
State object to 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 = String.Empty;
private static void Startclient () {
Connect to a remote device.
try {
Establish the remote endpoint for the socket.
The name of the
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: {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 receiving the data from the remote device.
Client. BeginReceive (state.buffer, 0, stateobject.buffersize, 0,
New AsyncCallback (ReceiveCallback), state);
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}
private static 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 is more data, and 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) {
Console.WriteLine (E.tostring ());
}
}
private static void Send (Socket client, String data) {
Convert the string data to byte 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 example program creates a server that receives a connection request from a client. The server is generated with an asynchronous socket.
Therefore, the execution of the server application is not suspended while waiting for a connection from the client. The application receives a string from the client,
Display the string in the console, and then echo the string back to the client. The string from the client must contain the string "<EOF>".
To emit a 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[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 a 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 is more data, and so store the "data received 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 of the data has been read from the
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 received. 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 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;
}
}
Related Article

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.