C # asynchronous socket

Source: Internet
Author: User

. Net socket development-asynchronous socket

In the development of. Net-based network server, the most frequently used and heard is probably asynchronous socket. The performance of asynchronous socket is much higher than that of synchronization, but the code writing is complicated. Therefore, asynchronous socket is also a topic discussed on the network.

Today, we will discuss how to use asynchronous socket to develop network applications. We will discuss two issues before that.

I. How does asynchronous socket work:

How does asynchronous socket work? This problem is explained by receiving a message. First, the program sends a request to the system to receive data, and specifies a data buffer and callback function for it. The callback function is used to indicate how the data will be processed when it arrives, then our program continues to run. When data arrives, the system reads the data into the buffer zone and executes the callback function to process the message. We do not need to worry about when this message will arrive.

Ii. Under what circumstances should we use asynchronous socket:

Some people think that the performance of asynchronous socket is much higher than that of synchronous socket. asynchronous socket should be used in various environments. In some environments. Asynchronous reverse synchronization has lower performance than synchronization. Under what circumstances will this happen?

1. client socket.

2. The number of server connections is relatively small.

3. Many connections, but all are short connections.

In these environments, synchronous socket not only simplifies the code, but also has no lower performance than asynchronous socket. However, when there are many server connections and long connections, we need to use asynchronous socket.

Now let's take a look at how to use asynchronous socket programming.

First, we need to establish a socket for listening:

Socket _ listener = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );

Ipendpoint localep = new ipendpoint (_ address, _ port );

_ Listener. BIND (localep );

_ Listener. Listen (100); then create a thread to process client connection requests:

Let's take a look at the definition of the callback function:

Private void effececallback (iasyncresult AR)

{

Userinfo info = (userinfo) Ar. asyncstate;

Socket handler = info. Socket;

Int readcount = 0;

Try

{

Readcount = handler. endreceive (AR); // call this function to end the receipt and return the received data length.

}

Catch (socketexception) // close the connection if a socket exception occurs.

{

Closesocket (Info); // This function is used to close the client connection.

Return;

}

Catch {}

If (readcount> 0)

{

Byte [] buffer = new byte [readcount];

Buffer. blockcopy (info. buffer, 0, buffer, 0, readcount );

Analyzer (Info, buffer); // This function is used to process received information.

Try

{

Handler. beginreceive (info. buffer, 0, info. Buffer. length, socketflags. None, new asynccallback (receivecallback), Info); // deliver the next receiving request to the System

}

Catch (socketexception) // close the connection if a socket exception occurs.

{

Closesocket (Info );

}

Catch

{

}

}

Else // If 0 bytes of data are received, the client closes the socket.

{

Closesocket (Info );

}

}

Next, let's take a look at how to send data to the client:

Public void send (Socket socket, byte message)

{

Try

{

Info. socket. beginsend (message, 0, _ byte. length, socketflags. none, new asynccallback (sendcallback), Info); // a data sending request is sent to the system and a callback function is specified.

}

Catch (socketexception ex)

{

Closesocket (Info );

}

Catch

{}

} Define the sending callback function:

Private void sendcallback (iasyncresult AR)

{

Userinfo info = (userinfo) Ar. asyncstate;

Try

{

Info. Socket. endsend (AR); // call this function to end sending.

}

Catch

{

}}

Well, the entire process of listening, receiving, and sending is complete. It's easy. Now, it should be noted that the accept for receiving client connection is synchronized here. I personally think it is better to use synchronization here than asynchronous. This is because the code is simple and there is no performance loss.

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.