C # asynchronous socket communication (rebuilding LAN chat gadgets)

Source: Internet
Author: User

May 1 was at home for a while <restructuring manual> and wanted to take the previously writtenCodeI tried to improve and think of the LAN chat tool I wrote last summer. Now I can see that the code I wrote was unsightly. the most incredible thing is that I used "multithreading" to process network requests, now I think the asynchronous method should be used.

Main Design

Brief Description

The left part indicates the client process, and the right part indicates the server process. the client has fewer steps than the server before establishing a connection. After a successful connection is established, both the client and the server have a communicatesocket to communicate with the other Party, such as sending, receiving, and sending a file, receiving files.

server , declare serversocket, bind an IP address, and specify the communication port of this IP address, for example, 127.0.0.1: 9050, serversocket can listen to connection requests sent from multiple IP addresses. The parameters of the listener (Listen) method can set the maximum number of connection requests allowed. then, call the beginaccept method. If a client sends a connection request, a new communicatesocket is defined to communicate with the client. then you can use communicatesocket. the beginsend () method sends data to the client, communicatesocket. beginreceive () can receive data from the client.

client has a communicatesocket bound with an IP address and an unused port. The ipendpoint serverip address is defined to indicate the IP address and port of the server socket, in this way, communication between the port and the port can be performed. Next, you can try communicatesocket. beginconnect (serverip), after the connection is successful, you can send and receive data, communicatesocket. beginsend (), communicatesocket. beginreceive ().

Some asynchronous methods have two implementation methods, such as beginaccept () and acceptasync (). What are the differences between these two methods?The method starting with begin and end is implemented asynchronously using the APM (asynchronous programming model) design method. The method ending with async is called EAP (Event-based Asynchronous Pattern) the Asynchronous Operation implemented by the design method.

Code Part 1. socketfunc class

Socketfunc is an abstract class. The method for establishing a connection between the server and the client is different. The other classes are the same. Therefore, put the same part in this class.

Public abstract class socketfunc {// whether it is a server or a client, use this socket to establish a connection. Public socket communicatesocket = NULL; // The method for establishing a connection between the server and the client is slightly different, the subclass will overload public abstract void access (string IP, system. action accessaciton); // The message sending function public void send (string message) {If (communicatesocket. connected = false) {Throw new exception ("no connection established, message cannot be sent");} byte [] MSG = encoding. utf8.getbytes (Message); communicatesocket. beginsend (MSG, 0, MSG. length, socketflags. none, ar =>{}, null);} // The Public void receive (system. action <string> receiveaction) {// if the message exceeds 1024 bytes, the received message is divided into (total byte length/1024 + 1) byte [] MSG = new byte [1024]; // receives the message communicatesocket asynchronously. beginreceive (MSG, 0, MSG. length, socketflags. none, AR => {// when the other party disconnects, the socket exception // an existing connection was forcibly closed by the remote host communicatesocket is thrown here. endreceive (AR); receiveaction (encoding. utf8.getstring (MSG ). trim ('\ 0', ''); receive (receiveaction) ;}, null );}}
2. serversocket: socketfunc class

Inherited from the socketfunc class. The access method is overloaded in the class.

 
Public class serversocket: socketfunc {// server-side overload access function public override void access (string IP, system. action accessaciton) {socket serversocket = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); // The pre-used IP address and port ipendpoint serverip = new ipendpoint (IPaddress. any, 9050); // bind the IP address serversocket set by the server. BIND (serverip); // sets the number of listeners serversocket. listen (1); // asynchronously receives the connection request serversocket. beginaccept (AR => {base. communicatesocket = serversocket. endaccept (AR); accessaciton () ;}, null );}}
3. clientsocket: socketfunc class

Inherited from the socketfunc class. The access method is overloaded in the class.

Public class clientsocket: socketfunc {// The access function public override void access (string IP, system. action accessaciton) {base. communicatesocket = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); base. communicatesocket. BIND (New ipendpoint (IPaddress. any, 9051); // server IP address and port ipendpoint serverip; try {serverip = new ipendpoint (IPaddress. parse (IP), 9050);} catch {Throw n EW exception (string. Format ("{0} is not a valid IP address! ", Ip);} // The client is only used to send information to the specified server. You do not need to bind the local IP address and port, and do not need to listen to try {base. communicatesocket. beginconnect (serverip, ar =>{ accessaciton () ;}, null) ;}catch {Throw new exception (string. format ("failed to connect {0! ", Ip ));}}}
Program

Source code download

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.