Detailed explanation C # socket Asynchronous Communication Instance _c# tutorial

Source: Internet
Author: User

TCPServer

1, the use of communication channels: socket

2, the use of the basic functions:

①bind,

②listen,

③beginaccept

④endaccept

⑤beginreceive

⑥endreceive

3, function parameter description

 Socket listener = new socket (addressfamily.internetwork,

      SocketType.Stream, protocoltype.tcp);

The parameters used for the new socket are the predefined amounts of the system and are selected for use directly.

Listener. Bind (Localendpoint);

Localendpoint represents a fully defined terminal, including IP and port information.

New IPEndPoint (Ipaddress,port)

//ipadress.parse ("192.168.1.3")

listener. Listen (100);

Listening

  Listener. BeginAccept (

          new AsyncCallback (acceptcallback),

          listener);

AsyncCallback (Acceptcallback), once the callback function on the connection is acceptcallback. When the system calls this function, the input parameter that is automatically given is iasyncresoult type variable AR.

Listener, a container for connecting behavior.

Socket handler = listener. Endaccept (AR);

Complete the connection and return to the socket channel at this time.

Handler. BeginReceive (state.buffer, 0, stateobject.buffersize, 0,

      new AsyncCallback (Readcallback), state);

Bytes received, 0, byte length, 0, callback function when received, the container that receives the behavior.

========

The structure type of the container is:

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 ();
}

The container is at least one socket type.

===============

 Read data from the client socket. 

    int bytesread = handler. EndReceive (AR);

Complete the connection once. The data is stored in State.buffer, bytesread for the length of the read.

Handler. BeginSend (bytedata, 0, bytedata.length, 0,

      new AsyncCallback (Sendcallback), handler);

Send data Bytedata, callback function Sendcallback. Container handler

int bytessent = handler. Endsend (AR);

Sent, BytesSent bytes sent.

4 Program Structure

Main program:

    byte[] bytes = new byte[1024];
    IPAddress ipaddress = Ipaddress.parse ("192.168.1.104");
    IPEndPoint localendpoint = new IPEndPoint (ipaddress, 11000);

    Generates a TCP socket
    socket listener = new socket (addressfamily.internetwork,
      SocketType.Stream, PROTOCOLTYPE.TCP);

    Listener. Bind (localendpoint);
    Listener. Listen (m);

    while (true)
    {

      //Set the event to nonsignaled state.
      Alldone.reset ();

      Open the asynchronous listening socket
      Console.WriteLine ("Waiting for a Connection");
      Listener. BeginAccept (
           new AsyncCallback (acceptcallback),
           listener);

      Let the program wait until the connection task is complete. Place the Alldone.set () statement in the appropriate place in the acceptcallback.
      Alldone.waitone ();
      }

  Console.WriteLine ("\npress ENTER to continue");
  Console.read ();

Connection behavior callback function Acceptcallback:

  public static void Acceptcallback (IAsyncResult ar)

  {

    //Add this command to allow the main thread to continue.

    Alldone.set ();

    Gets the socket socket

    listener = (socket) AR for the client request. asyncstate;

    Socket handler = listener. Endaccept (AR);

    Build a container and use it to receive commands.

    StateObject state = new StateObject ();

    State.worksocket = handler;

    Handler. BeginReceive (state.buffer, 0, stateobject.buffersize, 0,

      new AsyncCallback (Readcallback), state);

  

callback function for read behavior readcallback:

 public static void Readcallback (IAsyncResult ar) {String content = STRING.E

    Mpty;

    Gets the state and the socket object from the asynchronous state object. StateObject state = (stateobject) ar.

    asyncstate;

    Socket handler = State.worksocket; 

    Reads data from a client socket. int bytesread = handler.

    EndReceive (AR); if (Bytesread > 0) {//If the data is received, save it State.sb.Append (Encoding.ASCII.GetString state.buffer, 0, bytes

      Read));

      Check to see if there is a closing tag, and if not, continue reading the content = State.sb.ToString (); if (content).

        IndexOf ("<EOF>") >-1) {//All data read complete. Console.WriteLine ("Read {0} bytes from socket.") \ n Data: {1} ", content.

        Length, content);

        Response to the client.

      Send (handler, content);

        else {//Receive not completed, continue receiving. Handler.

      BeginReceive (state.buffer, 0, stateobject.buffersize, 0, New AsyncCallback (Readcallback), state); }

    }

  }

To send a message to a client:

private static void Send (Socket handler, String data)

  {

    //message format conversion.

    byte[] Bytedata = Encoding.ASCII.GetBytes (data);

    Start sending data to remote destinations.

    Handler. BeginSend (bytedata, 0, bytedata.length, 0,

      new AsyncCallback (Sendcallback), handler);

The private static void Sendcallback (IAsyncResult ar)

  {

   

      //Gets the socket from the state object.

      Socket handler = (socket) ar. asyncstate;

      Complete data send

      int bytessent = handler. Endsend (AR);

      Console.WriteLine ("Sent {0} bytes to client.", bytessent);

      Handler. Shutdown (Socketshutdown.both);

      Handler. Close ();

  }

In the callback function of various behaviors, the corresponding socket is obtained from the AsyncState property of the input parameter. Use (Socket) or (stateobject) to cast. The BeginReceive function uses a container that is state because it needs to store the transmitted data.

The rest of the container that receives or sends functions is also a socket.

Complete code

  Using System;
  Using System.Net;
  Using System.Net.Sockets;
  Using System.Text;
  
  Using System.Threading;
   State object for reading client data asynchronously the public class StateObject {//client socket.
   Public Socket worksocket = null;
   Size of receive buffer.
   public const int buffersize =;
   Receive buffer.
   Public byte[] buffer = new Byte[buffersize];
   Received data string.
 Public StringBuilder sb = new StringBuilder ();
   The public class Asynchronoussocketlistener {//Thread signal.
 
   public static ManualResetEvent alldone = new ManualResetEvent (false); Public Asynchronoussocketlistener () {} public static void Startlistening () {//Data buffer for Incomi
     ng data.
 
     byte[] bytes = new byte[];
     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 = Ipaddress.parse ("...");
 
     IPEndPoint localendpoint = new IPEndPoint (ipaddress,);
     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 ();
         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 ();
     The catch (Exception e) {Console.WriteLine (e.tostring ());
     } Console.WriteLine ("\npress ENTER to continue"); Console.read ();
     The public static void Acceptcallback (IAsyncResult ar) {//Signal is 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,, Stateobject.buffersize,, 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 >) {//There might is more data, and so store the data received so far.       State.sb.Append (Encoding.ASCII.GetString (State.buffer, bytesread)); Check for End-of-file tag.
       If It isn't there, read//More data.
       Content = State.sb.ToString (); if (content). IndexOf ("<EOF>") >-) {//All of the data has been read from the//client.
         Display it on the console. Console.WriteLine ("Read {} bytes from socket.") \ n Data: {} ', content.
 
         Length, content);
         Echo the data back to the client.
       Send (handler, content); else {//Not all data received.
         Get more. Handler.
       BeginReceive (State.buffer,, Stateobject.buffersize,, 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, Bytedata.length, 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 {} 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; }
 
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.