C # Asynchronous socket communication

Source: Internet
Author: User

0. Based on the previous C # socket (synchronous) communication, after several great God comments, it was found that there are quite a few places, so write an improved version of C #-based asynchronous socket communication. Further deepen the use and understanding of the socket. The client and server are all using the WPF interface, which realizes the heartbeat, disconnection and the function of multiple clients on a service side.

I. Service-side

1.1 First create a socket instance and bind to the 20000 port number, start listening and set the maximum number of listeners through the Listen method.

// Create a new socket server instance and bind to port 20000  This New sockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); this. Socketserver.bind (new20000)); // set maximum number of listeners this. Socketserver.listen (ten);

1.2 began to listen to the client asynchronously, using BeginAccept and endaccept, when there is a client connection will automatically call the callback function, at this time to start the heartbeat and the client's socket and heartbeat and other information into the global dictionary.

 This. socketserver.beginaccept (AR ={Socket _socket=socketserver.endaccept (AR); //Start HeartbeatSystem.Timers.Timer Heartbeattimer =NewSystem.Timers.Timer (); Heartbeattimer.interval=600000; Heartbeattimer.elapsed+=NewSystem.Timers.ElapsedEventHandler ((s, e) = =Heartbeattimerisup (S, E, _socket));    Heartbeattimer.start (); Socketinfo Info=NewSocketinfo (); Info.heartbeattimer=Heartbeattimer;  This. Socketinfodic.add (_socket, info); //Start receiving dataThdrevmethod (_socket); //start the next listen .listensocket ();},NULL);

1.3 Receive data, when there is a successful client connection in the previous step, you can open the asynchronous receive data from the client, using BeginReceive and EndReceive, when received from the client's data, the callback function is automatically called. Due to the size of the received data is not certain, so here each receive 1024 bytes, and then the received data splicing together, using the available property, for the number of bytes readable, if less than or equal to 0, indicating that the data received is complete.

Socket _socket = obj asSocket;if( This. Socketinfodic.containskey (_socket)) {Socketinfo Socketinfo=Socketinfodic[_socket]; //start receiving Messages_socket. BeginReceive (Socketinfo.tempbyte,0, SocketInfo.tempByte.Length, socketflags.none, AR =    {        Try        {            intResint =_socket.            EndReceive (AR); Socketinfo.contentbyte=SocketInfo.contentByte.Concat (socketinfo.tempbyte).            ToArray (); Socketinfo.tempbyte=New byte[1024x768]; if(_socket. Available <=0)            {                intActuallength = SocketInfo.contentByte.Length-(SocketInfo.tempByte.Length-resint); stringres = Encoding.Default.GetString (Socketinfo.contentbyte,0, actuallength); Socketinfo.contentbyte=New byte[0];        } thdrevmethod (_socket); }        Catch(SocketException sex) {if(Sex.) Socketerrorcode = =socketerror.connectionreset) {//when the client disconnects, remove the client from the list            if( This. Socketinfodic.containskey (_socket)) {                     This. Socketinfodic.remove (_socket); }            }        }        Catch(Exception ex) {MessageBox.Show ("An exception occurred in the program:"+ex); }    }, NULL);}

1.4 Send data, using BeginSend and Endsend, send a successful call callback function, where the Endsend () method returns the number of bytes sent successfully

byte [] bytestr =0, bytestr.length, Socketflags.none, AR +=    {null);

Two. Client

2.1 Create a new socket instance and begin to connect asynchronously to the server, using BeginConnect and EndConnect, the successful connection will automatically invoke the callback function, at this point, the heartbeat can start, receive data sent.

//Create a new client instance and connect to the port number where the server is located This. socketclient =Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);//Connect to the service side This. Socketclient.beginconnect ("127.0.0.1",20000, AR ={    Try    {         This. Socketclient.endconnect (AR);  This. Thdrevmethod (); }    Catch(SocketException sex) {if(Sex.) Socketerrorcode = =socketerror.connectionrefused) { This. Reconnecttimer.start ();  This. Heartbeattimer.stop (); }    }    Catch(Exception) { This. Heartbeattimer.stop (); Throw; }}, NULL);

2.2 Sending and receiving data (similar to client)

Three. Running the sample

Four. Summary

If the above description, or the code logic has any problems, I hope that the great God help point out, thank you!

Some of the areas to note are as follows:

4.1. When receiving data asynchronously, because the received data size is indeterminate, so tentatively only receive 1024 bytes at a time, according to available, if the received data is greater than 1024 bytes, then stitching the resulting data.

4.2 In the server, each receive 1024 bytes of byte[] cannot be defined as a global variable, and need to correspond to each socket client one by one, or receive messages from more than one client error. (That's what I understand here.)

The source code is as follows: Asyncsocketdemo.rar

C # Asynchronous socket communication

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.