C#socket network communication Asynchronous processing

Source: Internet
Author: User

C#socket network communication asynchronous processing SocketAsyncEventArgs asynchronous socket operation

1. Simple implementation of the service side:


Code:

    Public partial class Form_server:form {private socket socket;
        Public Form_server () {InitializeComponent ();
                } private void Form_server_load (object sender, EventArgs e) {try { Gets the local IP address ipaddress ipaddress = Dns.gethostbyname (Dns.gethostname ()).
                ADDRESSLIST[0]; Txt_ip. Text = IPAddress.
            ToString (); The catch (Exception ex) {MessageBox.Show (ex).
            message);
            }//Open socket listening private void Btn_listent_open_click (object sender, EventArgs e) { try {if (string). IsNullOrEmpty (txt_ip.
                Text) {MessageBox.Show ("Please enter IP address"); //Turn on listening ipaddress IP = ipaddress.parse (txt_ip.
                Text); IPEndPoint localEP = new IPEndPoint (IP, int32.parse (tXt_port.
                Text));
                Socket = new Socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); Socket.
                Bind (LOCALEP); Socket.

                Listen (1000);
                Acceptasync asynchronous Way SocketAsyncEventArgs SocketAsyncEventArgs = new SocketAsyncEventArgs (); socketasynceventargs.completed + = new Eventhandler<socketasynceventargs> (socketasynceventargs_completed_
                Acceptasync);
                Socketasynceventargs.remoteendpoint = localEP;
                Socketasynceventargs.usertoken = socket; Socket.
               
                Acceptasync (SocketAsyncEventArgs); The message prompts this.lb_msg.
                Items.Add ("[Service side]:"); This.lb_msg.
            Items.Add ("Monitoring Success"); The catch (Exception ex) {MessageBox.Show (ex).
            message); }//Start an asynchronous operation to accept an incoming connection attempt void Socketasynceventargs_completed_acceptasync (ObjeCT serversocket, SocketAsyncEventArgs e) {//closed, overlapping operations aborted if (E.socketerror = = SocketError . operationaborted) {//closed, overlapping operation aborted this.lb_msg. Invoke (New Action () => {this.lb_msg.
                    Items.Add ("[Service end]:"); This.lb_msg.
                Items.Add ("Socketasynceventargs_completed_acceptasync: closed, overlapping operations terminated >socketerror:operationaborted");
                }));
            Return //This connection is reset by the remote peer if (e.socketerror = Socketerror.connectionreset && e.bytestransferred = = 0) {//This connection is reset by the remote peer computer this.lb_msg. Invoke (New Action () => {this.lb_msg.
                    Items.Add ("[Service end]:"); This.lb_msg.
                Items.Add ("Socketasynceventargs_completed_acceptasync: This connection is reset by a remote peer computer >socketerror:connectionreset");
                }));
Return            } if (e.lastoperation = = socketasyncoperation.accept) {T
                     
                    ry {Socket acceptsocket = E.acceptsocket; Starts an asynchronous request to receive data from the connected System.Net.Sockets.Socket object SocketAsyncEventArgs socketasynceventargsreceiveasy
                    NC = new SocketAsyncEventArgs ();
                    Socketasynceventargsreceiveasync.usertoken = AcceptSocket;
                    byte[] Receivebuff = new byte[1024 * 4];
                    Socketasynceventargsreceiveasync.setbuffer (receivebuff, 0, receivebuff.length); socketasynceventargsreceiveasync.completed + = new Eventhandler<socketasynceventargs> (socketAsyncEventArgs_
                    Completed_receiveasync);

                    Acceptsocket.receiveasync (Socketasynceventargsreceiveasync); The message prompts this.lb_msg.
               Invoke (New Action () => {         This.lb_msg.
                        Items.Add ("[Client]:"); This.lb_msg.
                    Items.Add ("connected successfully");
                })); The catch (Exception ex) {MessageBox.Show (ex).
                message);
                //Start an asynchronous operation to accept an incoming connection attempt, recursive e.acceptsocket = null; Socket.
            Acceptasync (e); //Start an asynchronous request to receive data void from the connected System.Net.Sockets.Socket object Socketasynceventargs_completed_receiv Easync (Object AcceptSocket, SocketAsyncEventArgs e) {//closed, overlapping operation aborted if (E.socketerror = = socketerror.operationaborted) {//closed, overlapping operation aborted this.lb_msg. Invoke (New Action () => {this.lb_msg.
                    Items.Add ("[Service end]:"); This.lb_msg.
       Items.Add ("Socketasynceventargs_completed_receiveasync: closed, overlapping operations terminated >socketerror:operationaborted");         }));
            Return //This connection is reset by the remote peer if (e.socketerror = Socketerror.connectionreset && e.bytestransferred = = 0) {//This connection is reset by the remote peer computer this.lb_msg. Invoke (New Action () => {this.lb_msg.
                    Items.Add ("[Service end]:"); This.lb_msg.
                Items.Add ("Socketasynceventargs_completed_receiveasync: This connection is reset by a remote peer computer >socketerror:connectionreset");
                }));
            Return
                } if (E.socketerror = = socketerror.success && e.buffer.length > 0) {

                    try {Socket socket = acceptsocket as socket; string ipaddress = socket.
                    Remoteendpoint.tostring ();

                    int lengthuffer = e.bytestransferred;
                    byte[] Receivebuffer = E.buffer;
     byte[] buffer = new Byte[lengthuffer];               Buffer.blockcopy (receivebuffer, 0, buffer, 0, lengthuffer);

                    String message = Encoding.UTF8.GetString (buffer); This.lb_msg. Invoke (New Action () => {this.lb_msg.
                        Items.Add ("[Client]:"); This.lb_msg.
                    Items.Add ("" + message);

                    })); Socket. Send (Encoding.UTF8.GetBytes (String).
                    Format ("received message {0}:{1}", DateTime.Now.ToString ("Yyyy/mm/dd HH:mm:ss"), messages)); Socket.
                Receiveasync (e); The catch (Exception ex) {MessageBox.Show (ex).
                message);
        ////close socket listening private void Btn_listent_close_click (object sender, EventArgs e) {try {if (socket!= null) {socket.
                Close (); } this.lb_msg.
                Items.Add ("[Service side]:"); This.lb_msg.
            Items.Add ("Shutdown Monitor succeeded"); The catch (Exception ex) {MessageBox.Show (ex).
            message); }
           
        }
    }

2. Simple implementation of the client:


Code:

    Public partial class Clientmainform:form {private Socket _socket;
        Public Clientmainform () {InitializeComponent ();
                }//Login private void Btn_login_click (object sender, EventArgs e) {try { IPAddress IP = ipaddress.parse (this.txt_ip.
                Text); IPEndPoint IPEndPoint = new IPEndPoint (IP, Int32.Parse (this.txt_port.

                Text));
                _socket = new Socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); _socket.

                Connect (IPEndPoint); This.lb_msg.
                Items.Add ("[Client]:"); This.lb_msg.

                Items.Add ("Connection Service side success");
                Opens a new Accept message asynchronous operation event SocketAsyncEventArgs SocketAsyncEventArgs = the newer SocketAsyncEventArgs ();
                Set the buffer size of the message byte[] Receivebuff = new byte[1024 * 4];
Socketasynceventargs.setbuffer (receivebuff, 0, receivebuff.length);                Socketasynceventargs.usertoken = _socket;
                Bind Callback Event socketasynceventargs.completed + = Socketasynceventargs_completed_receiveasync; _socket.
            Receiveasync (SocketAsyncEventArgs); The catch (Exception ex) {MessageBox.Show (ex).
            message);
        //Start an asynchronous request to receive data from the connected System.Net.Sockets.Socket object. void Socketasynceventargs_completed_receiveasync (object sender, SocketAsyncEventArgs e) {//closed, overlapping operations are Abort if (e.socketerror = = socketerror.operationaborted) {this.lb_msg. Invoke (New Action () => {this.lb_msg.
                    Items.Add ("[Client]:"); This.lb_msg.
                Items.Add ("Socketasynceventargs_completed_receiveasync: Closed, overlapping operation interrupted: operationaborted");
                }));
            Return //This connection is reset by the remote peer to the IF (e).SocketError = = Socketerror.connectionreset && e.bytestransferred = 0) {//This connection is by a remote peer Reset the this.lb_msg. Invoke (New Action () => {this.lb_msg.
                    Items.Add ("[Client]:"); This.lb_msg.
                Items.Add ("Socketasynceventargs_completed_receiveasync: This connection is reset by a remote peer: Connectionreset");
                })); 
            Return
            Socket socket = sender as socket; if (e.socketerror==socketerror.success&&e.buffer.length>0) {string IPAddress = Sock Et.
                Remoteendpoint.tostring ();

                int lengthuffer = e.bytestransferred;
                byte[] Receivebuffer = E.buffer;
                byte[] buffer = new Byte[lengthuffer];
                Buffer.blockcopy (receivebuffer, 0, buffer, 0, lengthuffer);


                String message = Encoding.UTF8.GetString (buffer); This.lb_msg. Invoke (New Action (() => {this.lb_msg.
                    Items.Add ("[Service end]:"); This.lb_msg.
                Items.Add ("" + message);
              
                })); Socket.
            Receiveasync (e); }//Send message private void Btn_sendmsg_click (object sender, EventArgs e) {if (s) Tring. IsNullOrEmpty (txt_msg.
            Text) {MessageBox.Show ("Please enter a message"); else {_socket. Send (System.Text.Encoding.UTF8.GetBytes (txt_msg).
            Text)); }
        }
    }


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.