. Net socket development (1) Synchronous socket implementation

Source: Internet
Author: User
Tags ipoint
. Net socket development-synchronous socket implementation: two examples today, let's talk about the. NET network application Program Many people think that synchronous sockets 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. 1. The number of clients is relatively small: 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. Code The performance will not drop too much. 2. A large number of clients, but all of them are short connections: Short connections are the scenarios in which client connections are generated and disconnected after one sending and receiving is completed. 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: first create a socket and bind it to an endpoint and 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:

 

Code

Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Using System. net;
Using System. net. Sockets;
Using System. Threading;

Namespace Socketserver
{
///   <Summary>
/// Socket synchronous communication socket + thread
///   </Summary>
Public   Class Socketa
{
Socket server;
Public Socketa ()
{
// Create a socket to listen on client connections
Server =   New Socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Server. BIND ( New Ipendpoint (IPaddress. Any, 9999 ));
Server. Listen ( 100 );
Console. writeline ( " Server startup ...... " );

//Then create a thread to process client connection requests
Thread th= NewThread (NewThreadstart (writeconnction ));
Th. Start ();
Console. Readline ();
}

Public   Void Writeconnction ()
{
Thread. currentthread. isbackground =   True ;
While ( True )
{
Socket s = Server. Accept ();
Ipendpoint ippoint = (Ipendpoint) S. remoteendpoint;
Console. writeline ( " Received connection from: "   + Ippoint. Address. tostring ());
// Then create a thread to accept the information
Thread th =   New Thread ( New Parameterizedthreadstart (writemsg ));
Th. start (s );
}
}

Public   Void Writemsg ( Object OBJ)
{
Thread. currentthread. isbackground =   True ;
If (OBJ ! = Null )
{
Socket socket = (Socket) OBJ;
Byte [] BYT = New   Byte [ 1024 ];
While ( True )
{
Int Getlength = Socket. Receive (BYT );
If (Getlength > 0 )
{
Ipendpoint ippoint = (Ipendpoint) socket. remoteendpoint;
String Address = Ippoint. Address. tostring ();
String MSG = System. Text. encoding. utf8.getstring (BYT, 0 , Getlength );
Console. writeline ( " Received from "   + Address + " Message: " + MSG );

Socket. Send (BYT, getlength, socketflags. None );
}
}
}
}

}
}

 

Now let's take a look at the second requirement: We will use another method to implement this solution. Why not use the previous method to implement it? 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:

 

Code

Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Using System. net;
Using System. net. Sockets;
Using System. Threading;

Namespace Socketserver
{
///   <Summary>
/// Socket synchronous communication socket + thread
/// A small number of clients
///   </Summary>
Public   Class Socketb
{
Socket server;
Public Socketb ()
{
// Create a socket to listen on client connections
Server =   New Socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Server. BIND ( New Ipendpoint (IPaddress. Any, 8888 ));
Server. Listen ( 100 );
Console. writeline ( " Server startup ...... " );

// Create a thread pool
Thread [] ths = New Thread [ 30 ];
For ( Int I =   0 ; I < Ths. length; I ++ )
{
Ths [I] =   New Thread ( New Threadstart (waiteconnetion ));
}
Console. Readline ();
}

Public   Void Waiteconnetion ()
{
Byte [] BYT = New   Byte [ 1024 ];
Socket s = Server. Accept ();
Ipendpoint ipoint = (Ipendpoint) S. remoteendpoint;
String IP = Ipoint. Address. tostring ();
Console. writeline ( " Received connection from: "   + IP );
Int Getlength = S. Receive (BYT );
If (Getlength > 0 )
{
String MSG = System. Text. encoding. utf8.getstring (BYT );
Console. writeline ( " Received Information " + IP + " From " + MSG );
S. Send (BYT, getlength, socketflags. None );
}
S. Shutdown (socketshutdown. Both );
S. 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.