. Net socket development-synchronous socket implementation: Two Examples

Source: Internet
Author: User

Source: China IT lab

Today, let's talk about it. Net network applicationsProgramMany people think that synchronous socket should not be used in the network application server socket. yes, this is the case in most cases, but in some scenarios, we may get more results by using synchronous socket. For example, in the following two scenarios, we can consider using synchronous sockets.

I. A small number of clients:

A relatively small number means that the number of clients that will connect to the server at the same time is generally less than 50. In this case, we can consider using synchronous socket + thread to implement our server. This will make the logic clearer.CodeThe performance will not drop too much.

2. A large number of clients but all are short connections:

A short connection is a scenario where client connections are disconnected after a sending or receiving operation. For example, HTTP is a short connection. HTTP establishes a socket connection when the client sends a request and sends a URL request through the socket. After the server completes the request and returns the corresponding page, the connection is disconnected. In this scenario, we can also use synchronous socket to meet our needs.

So we should implement the two requirements I mentioned above. For these two requirements, I will adopt different solutions to achieve them.

First, let's look at the first requirement. Here I use socket + thread to implement it. The basic process is as follows:

Create a socket and bind it to an endpoint to start listening. Next, we create a thread in which we use an infinite loop to receive connection requests from the client. After receiving a request, create a new thread for the client and use an infinite loop to receive data from the client. Let's take a look at the Code:

First, we create a socket to listen on the client connection:

Socket listener = new socket (addressfamily. InterNetwork,
Sockettype. Stream, protocoltype. TCP); ipendpoint LOCEP = new ipendpoint (IPaddress. Any, 2000); listener. BIND (LOCEP); listener. Listen (100 );

Then create a thread to process client connection requests:

Thread acceptthread = new thread (New threadstart (acceptworkthread); acceptthread. start (); Private void acceptworkthread ()... {thread. currentthread. isbackground = true; while (true )... {socket accept = listener. accept (); ipendpoint remoep = (ipendpoint) accept. remoteendpoint; string recstring = "received from" + remoep. address. tostring () + "connection. "; This. Invoke (New addlistitemhandler (this. addlistitem), new string []...
{Recstring}); thread fig = new thread (New parameterizedthreadstart
(Receiveworkthread); receivethread. Start (accept );}}

Finally, let's take a look at how to receive data:

Private void receiveworkthread (Object OBJ )... {thread. currentthread. isbackground = true; Socket socket = (socket) OBJ; byte [] buffer = new byte [1024]; while (true )... {int receivecount = socket. receive (buffer); If (receivecount> 0 )... {ipendpoint remoep = (ipendpoint) socket. remoteendpoint; string recstring = "from client" + remoep. address. tostring () +"
Message: "+ encoding. Default. getstring (buffer, 0, receivecount); this. Invoke (New addlistitemhandler (this. addlistitem), new string []
... {Recstring}); socket. Send (buffer, receivecount, socketflags. None);} else... {socket. Close (); break ;}}}

Now, the entire implementation is complete.

Now let's look at the second requirement:

We will use another method to implement this solution. Why not use the previous method? Let's analyze it. We know that in the previous implementation, a thread is created every time a client is accessed. If a large number of clients are accessed, too many threads will be created. However, if there are too many threads, Windows requires more CPU time to switch the context of the thread (this is why the previous implementation cannot access many clients ).

We know that in this solution, every connection is a short connection. And the order is fixed. All are: access-> receive-> send, then we can complete the entire process in a method. In this way, we can use the thread pool to implement what we need. Well, let's use the code:

First, we create a socket to listen on the client connection:

Socket listener = new socket (addressfamily. InterNetwork, sockettype. stream,
Protocoltype. TCP); ipendpoint LOCEP = new ipendpoint (IPaddress. Any, 2000); listener. BIND (LOCEP); listener. Listen (100 );

Next we will create a thread pool:

Thread [] clientthreadlist = new thread [30]; foreach (thread th in clientthreadlist )... {th = new thread (New threadstart (clientworkthread); th. start ();}

Finally, let's see what the thread has to do:

 private void clientworkthread ()... {byte [] buffer = new byte [1024]; while (true )... {Socket socket = listener. accept (); string recstring = "received from" + remoep. address. tostring () + "connection. 
"; this. invoke (New addlistitemhandler (this. addlistitem), new string []
... {recstring}); int rececount = socket. receive (buffer); If (rececount> 0 )... {string recstring = "from client" + remoep. address. message of tostring () + "
:" + encoding. default. getstring (buffer, 0, receivecount); this. invoke (New addlistitemhandler (this. addlistitem), new string []
... {recstring}); socket. send (buffer, rececount, socketflags. none);} socket. shutdown (socketshutdown. both); socket. close () ;}

Why are we doing this?

First, we created a socket to listen for client connection requests, and then we created a thread pool with 30 threads. In each thread, accept, receive, send, and close () are implemented to connect, receive, send, and close the connection.

Now we assume that a client is connected to the server, and a thread will access the request and start to receive the data sent from the client. After receiving the data, the client will process the data and send it to the client, close the connection and wait for the connection again. The other 29 threads still process the waiting access status because they do not have an accept request.

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.