Asynchronous implementation of socket communication programming in C #

Source: Internet
Author: User

Based on the synchronous communication of socket in C #, this paper analyzes and studies the realization method of socket asynchronous programming, in order to understand the basic principle of socket programming and to enhance the understanding of the related content of network game development. what is asynchronous for socket programming is implemented

The asynchronous implementation of the so-called socket programming refers to the asynchronous process to implement the socket programming, then what is asynchronous process, we have completed a call through the state, notifications and callbacks to inform the caller of the way to become an asynchronous process, in other words, in the asynchronous process when a method is invoked, The caller is not able to get the result immediately, and the caller cannot get the result of the call until the method has been called. What is the advantage of doing so? The answer is high efficiency. I believe you can remember that we are in the "C # Socket Communication programming Synchronization implementation" This article uses multithreading to achieve a simple chat case, in this case we need to open two threads to continuously monitor the client's connection and client messages, such efficiency is certainly very low. So now that we can work through the asynchronous process to solve this problem, let's look at how to implement the asynchronous communication of the socket. How to implement socket asynchronous communication Service Side The basic process creates a socket-bound socket's IP and port number--bind () the socket is in a listening state waiting for a connection request from the client--listen () when the request arrives, the BeginAccept () and Endaccept () methods are used to accept the request. Returns a new socket using the BeginSend ()/endsend and BeginReceive ()/endreceive () two sets of methods to send and receive communication with the client, and wait for the new connection request to close the socket code sample

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Net;

Using System.Net.Sockets;
            Namespace Asyncserver {public class Asynctcpserver {public void Start () {//Create socket
            IPEndPoint ipe = new IPEndPoint (Ipaddress.parse ("127.0.0.1"), 6065);
            Socket socket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); Binding ports and IP Sockets.
            Bind (IPE); Sets the listening socket.
            Listen (10);
        Connect client asyncaccept (socket); ///<summary>///Connect to client///</summary>///<param name= "socket" >< /param> private void asyncaccept (socket socket) {socket. BeginAccept (asyncresult => {//GET client socket SOCKET client = socket.
                Endaccept (asyncresult); Console.WriteLine (String. Format (Client {0} requests a connection ...), client. RemOteendpoint));
                Asyncsend (client, "Server receives connection request"); Asyncsend (client, String. Format ("Welcome you {0}", client.)
                Remoteendpoint));
            Asyncreveive (client);
        }, NULL); ///<summary>///receive messages///</summary>///<param name= "Client" ></p
            aram> private void asyncreveive (socket socket) {byte[] data = new byte[1024]; try {//start receiving message socket. BeginReceive (data, 0, data.) Length, Socketflags.none, asyncresult => {int length = socket.
                    EndReceive (asyncresult); Console.WriteLine (String.
                Format ("client sends message: {0}", Encoding.UTF8.GetString (data));
            }, NULL); The catch (Exception ex) {Console.WriteLine (ex).
            message);
   }///<summary>///send messages     </summary>///<param name= "Client" ></param>///<param name= "P" ></par am> private void Asyncsend (Socket client, string p) {if (client = null | | p = = string.
            Empty) return;
            byte[] data = new byte[1024];
            data = Encoding.UTF8.GetBytes (p); try {//Start sending message client. BeginSend (data, 0, data.) Length, Socketflags.none, asyncresult => {//completion message send int length = client.
                    Endsend (asyncresult); Output Message Console.WriteLine (string.
                Format ("server sends message: {0}", p));
            }, NULL);
            catch (Exception e) {Console.WriteLine (e.message); }
        }
    }
}
Client Basic ProcessCreate sockets and ensure consistency with the server's ports use the BeginConnect () and EndConnect () methods to send connection requests to the service side using BeginSend ()/endsend and BeginReceive ()/endreceive () Two sets of methods to send and receive communications with the server close socket code Example
Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Net;

Using System.Net.Sockets; Namespace Asyncclient {public class Asynctcpclient {///<summary>///connect to server///& lt;/summary> public void Asynconnect () {//port and IP ipendpoint ipe = new Ipendpoin
            T (Ipaddress.parse ("127.0.0.1"), 6065);
            Create socket Socket client = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); Start connecting to the server client. BeginConnect (IPE, asyncresult => {client.
                EndConnect (asyncresult);
                Send a message to the server Asynsend (client, "Hello I am a customer");
                Asynsend (client, "first message");
                Asynsend (Client, "second message");
            Accept Message asynrecive (client);
        }, NULL); ///<summary>///send messages///</summary>///<pAram Name= ' socket ' ></param>///<param name= ' message ' ></param> public void Asynsend (S Ocket socket, String message) {if (socket = = NULL | | message = = string.
            Empty) return;
            Encoded byte[] data = Encoding.UTF8.GetBytes (message); try {socket. BeginSend (data, 0, data.) Length, Socketflags.none, asyncresult => {//complete send message int length = socket.
                    Endsend (asyncresult); Console.WriteLine (String.
                Format ("client sends messages: {0}", message));
            }, NULL); The catch (Exception ex) {Console.WriteLine ("Exception information: {0}", ex.)
            message); }///<summary>///receive message///</summary>///<param name= "socket" ></param> public void asynrecive (socket socket) {byte[] data = new byTE[1024]; try {//start receiving data socket. BeginReceive (data, 0, data.) Length, Socketflags.none, asyncresult => {int length = socket.
                    EndReceive (asyncresult); Console.WriteLine (String.
                    Format ("Received Server message: {0}", Encoding.UTF8.GetString (data));
                Asynrecive (socket);
            }, NULL); The catch (Exception ex) {Console.WriteLine ("Exception Information:", ex.)
            message);
 }
        }
    }
}

Generally speaking, the logic of socket asynchronous programming is more explicit, because we just need to write a callback function for each process. So what's the effect of this example? Let's take a look at its demo effect:

Summary

Compared to the case of synchronous programming with sockets, today's case is probably just a simple application to the asynchronous programming content of the socket, since bloggers have not yet written a program that can be used for interactive chats. In asynchronous programming of sockets, the server does not need to create a separate thread for a client to maintain its connection, but one problem is that bloggers do not know how to implement an instance of multiple-client asynchronous programming. If a friend knows how to achieve, but also hope to be able to tell me, after all, learning is a mutual promotion process AH. Well, the last thing I want to say is that the blogger is studying the writing of asynchronous method calls in asynchronous programming of sockets. We know that the method in asynchronous programming of sockets occurs in pairs, each of which has a callback function, and for the callback function, there are two ways to do this, taking the BeginConnect method as an example:

M_socket.beginconnect (This.m_ipendpoint, 
        new AsyncCallback) (this. Connectcallback), 
        this.m_socket);//Where connectcallback is a callback function

Or

M_socket.beginconnect (this.m_ipendpoint,asyncresult=>
{
    //Add more code here
},null)

Why do bloggers say these two ways here, for two reasons:
* The second formulation is more concise and eliminates the need to construct containers to pass sockets and messages because they are all local variables. If we use the first method, because the main function and the callback function are two different functions, you need to access the values in the container through the IAsyncResult interface if you want to share the variables, which obviously increases our workload.
* The second is more elegant, which seems to be some kind of advanced syntax in the C # language, which I forget, anyway, I often see the shadow of this writing in LINQ.

Combined with the above two views, bloggers still suggest that you use the second way, bloggers intend to have the time to write before the program again, to see if you can find out the problem in the code. Well, today's content is like this, thank you, I hope you like.

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.