Java Socket parameter Test-backlog (i)

Source: Internet
Author: User

Before doing the project, just use spring-integration TCP/IP components, in the process of defining serversocket, there is a parameter backlog is more prominent, through the online inspection, Just know that this is the ServerSocket parameter in native java. Through the API to know, ServerSocket construction parameters: public serversocket (int port,int backlog), the API for the backlog parsing is this: requested maximum length of The queue of incoming connections; means the maximum capacity of the TCP connection request queue. The initial understanding is that if serversocket is too much to handle, subsequent client connections will be placed in the blocking queue, and subsequent connections will be rejected when the queue is full (exceeding the capacity defined by the backlog, which defaults to 50).

1. First the code, and then the conclusion:

Server side:

 Public classTestbacklog { Public Static voidMain (string[] args)throwsIOException, interruptedexception {intBacklog = 3; ServerSocket ServerSocket=NewServerSocket (5000, backlog); //This causes the client's connection to be blocked, and the request connection is placed in the request queue, and the capacity of the requesting queue is the value of the backlog//when the program starts, sleep here for 50 seconds, start the client immediately, the client every second from the second, when the third one can not get to ServerSocket//can only wait, the first two connections have been obtained ServerSocket connection, only wait for these two processing is finished, the next third will get the connection, processing (can be obtained from the client output this conclusion)Thread.Sleep (50000);//simulate server-side processing of high-latency tasks         while(true) {Socket Socket=serversocket.accept (); InputStream is=Socket.getinputstream (); OutputStream OS=Socket.getoutputstream (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (IS)); PrintWriter out=NewPrintWriter (Newoutputstreamwriter (OS)); intLength =-1; Char[] buffer =New Char[200];  while( -1! = (length = br.read (buffer, 0, Buffer.length))) {String String=NewString (buffer, 0, length); System.out.println ("Testbacklog receive String" + socket.getinetaddress () + ":" + socket.getlocalport () +string); Out.write ("Server welcome!");                Out.flush ();                            Socket.shutdownoutput ();            } out.close ();            Br.close ();        Socket.close (); }    }}

Client side:

 Public classTcpClient { Public Static voidMain (string[] args)throwsunknownhostexception, IOException, interruptedexception { for(inti=0; i<10; i++) {Thread.Sleep (1000);//create port too fast, reduce creation rate            NewThread (NewClientthread ()). Start (); }    }}classClientthreadImplementsRunnable {@Override Public voidrun () {Try{Socket Client=NewSocket ("127.0.0.1", 5000); System.out.println ("Client Connected server"); InputStream is=Client.getinputstream (); OutputStream OS=Client.getoutputstream (); Os.write ("Clinet Hello world!". GetBytes ()); Client.shutdownoutput ();//This sentence is very important ah, if not, the service side of read () will always block                        intLength = 0; byte[] buffer =New byte[200];  while( -1! = (length = is.read (buffer, 0, Buffer.length))) {System.out.println ("Client"); String receivestring=NewString (buffer, 0, length); System.out.println ("Receivestring:" +receivestring); }        } Catch(Exception e) {e.printstacktrace (); }    }}

2. Step: Run on the Win7 64-bit machine, first start testbacklog,testbacklog after creating ServerSocket, will go to sleep state. Run TcpClient again immediately, once the client is connected to the server, it will be output in the console: client Connected servers

3. Observe the phenomenon and draw a conclusion: When the server creates the service, the main thread sleeps, sleeps for 50 seconds, and if you run TcpClient now, 10 clients will be created, what will happen? The reality is: the console only output three times: client connected server, that means that only three clients connected to the service side, just as the backlog set the request queue capacity, the subsequent client to connect, Throws an exception: Java.net.ConnectException:Connection Refused:connect (This is what happens in Windows, and it runs on the Mac only three times, but the other clients are not rejected, But until the connection times out). When the end of the server sleep, processing the first three client requests, and then the subsequent client requests processed (provided that the client's connection did not time out).

This experiment just validates the requested cache queue, and the client in the queue has established a connection with the server to wait for the server to process. But the client of the queue that is not in the back, will make a new Socket (IP, port), still struggling to connect with the server AH ~

Java Socket parameter Test-backlog (i)

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.