Socket asynchronous communication learning 2. socket Asynchronous Communication
Next, the server part adopts the asynchronous mode and creates an AsynServer class to store the socket server code. There are four methods:
There is a global socket, which is used in the following four methods.
Socket socket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
The class framework is as follows:
1. constructor: public AsynServer (IPEndPoint endpoint, int listenMaxNum)
Used to initialize the socket server. The IPEndPoint parameter is the end point of the socket binding, and the listenMaxNum parameter is the maximum length of the suspension of the listening queue. The Code is as follows:
Public AsynServer (IPEndPoint endpoint, int listenMaxNum) {socket. bind (endpoint); // Bind the end point socket. listen (listenMaxNum); // sets the maximum value of the suspended queue to the listenMaxNum Console when the socket is in the listening status. writeLine ("connecting to the client .... "); AsynAccept (); // start asynchronous listening // return socket ;}
2. asynchronous listening method public void AsynAccept ()
Public void AsynAccept () {socket. beginAccept (asyncResult => {socket = socket. endAccept (asyncResult); // the asynchronous listener is successful and the socket Console is returned. writeLine ("client {0} asynchronous connection successful", socket. remoteEndPoint. toString (); AsynReceive (); AsynSend ("Server: Hello, client! ") ;}, Null );}View Code
Note that the BeginAccept () method of the asynchronous socket must end with the EndAccept () method, and the EndAccept (asyncResult) will return the socket by calling back the asyncResult status information in BeginAccept, this socket is the socket connected to the client. You need to assign it to the global socket (which will be called later in the method ).
In addition, AsynAccept does not block the main thread because the system automatically opens a thread for the BeginAccept () method and blocks the thread until it receives the client connection and calls back the receiving code in the lamda expression.
Use the callback function written in lamda. If you are not familiar with it, please try it out. It is very convenient to use it :-)
When the connection succeeds, the client will receive the message (AsynReceive () is asynchronous and will not block the main thread), and send the greeting information (AsynReceive () and AsynSend () to the client () all are asynchronous and will not hinder the main thread ).
3. asynchronous Receiving Method private void AsynReceive ()
Private void AsynReceive () {byte [] data = new byte [1024]; // receives the cache string receiveStr; socket. beginReceive (data, 0, data. length, SocketFlags. none, asyncResult => {int length = socket. endReceive (asyncResult); if (length! = 0) {receiveStr = Encoding. ASCII. getString (data, 0, length); // obtain the information in the cache Console. writeLine (receiveStr); AsynReceive (); // continue to open a new thread to receive} else {Console. writeLine ("client {0}: Disable socket connection", socket. remoteEndPoint. toString (); // socket. remoteEndPoint. toString () is the Client IP address socket. close () ;}, null );}AsynReceive ()
4. asynchronous sending method public void AsynSend ()
Public void AsynSend (string msg) {byte [] data = Encoding. UTF8.GetBytes (msg); socket. beginSend (data, 0, data. length, SocketFlags. none, asyncResult => {int length = socket. endSend (asyncResult); Console. writeLine ("message send to {0} successfully", socket. remoteEndPoint. toString ();}, null );}Public void AsynSend (string msg)
Because the socket sends and receives data in the byte stream format, byte [] data = new byte [1024] is used to receive data, cache the received byte stream, and then use Encoding. ASCII. the GetString (data, 0, length) method converts bytes into string output, and sends the data to the string through byte [] data = Encoding. UTF8.GetBytes (msg) converts string information into byte streams for sending. The EndReceive () and EndSend () Methods return the number of bytes sent and received (int)
All of the above are the simplest and can only implement basic communication functions. It will be improved later on this basis to help beginners avoid detours. At that time, I learned to be dizzy-_-|
The next article is about using a client in a completely different mode from the server, synchronous mode.