How to use the socket interface in java

Source: Internet
Author: User
Tags ack memory usage

Backlog

For ServerSocket, configure the maximum client waiting queue for ServerSocket. The meaning of the waiting queue. First look at the following code

The code is as follows: Copy code
Public class Main {
Public static void main (String [] args) throws Exception {
Int port = 8999;
Int backlog = 2;
ServerSocket serverSocket = new ServerSocket (port, backlog );
Socket clientSock = serverSocket. accept ();
System. out. println ("revcive from" + clientSock. getPort ());
While (true ){
Byte buf [] = new byte [1024];
Int len = clientSock. getInputStream (). read (buf );
System. out. println (new String (buf, 0, len ));
        }
    }
}

This test code does not process the second client when processing a client for the first time. Therefore, except the first client, other clients are waiting for the queue. Therefore, this server can connect up to three clients, two of which are waiting queues. You can telnet localhost 8999 for testing.

This parameter is set to-1, which indicates no limit. The default value is 50, which is the maximum waiting queue. If you set no limit, be careful. If your server cannot process so many connections, when many clients connect to your server, every TCP connection will occupy the server's memory, and the server will crash.

In addition, even if you set backlog to 10, if your code is always Socket clientSock = serverSocket. accept (). Assume that our machine can process a maximum of 100 requests at the same time, with a total of 100 threads running. Then you can process clientSock in the thread pool of 100 threads, clientSock that cannot be processed will be queued, and the clientSock will become more and more in the end. This also means that the memory usage of our server is getting higher and higher (the client will definitely send data when connecting to the process, the data is saved to the TCP receiving cache on the server side. Therefore, if you cannot process so many requests, do not call serverSocket. accept () cyclically and without restrictions; otherwise, the backlog will not take effect. If there are too many requests, it will only bring your server down (I believe many people write this way, please note)

TcpNoDelay

Disable the nag algorithm and send data immediately. The Nags algorithm increases the efficiency of TCP/IP networks by reducing the packet transmission volume. When we call the following code, such:

The code is as follows: Copy code
Socket socket = new Socket ();
Socket. connect (new InetSocketAddress (host, 8000 ));
InputStream in = socket. getInputStream ();
OutputStream out = socket. getOutputStream ();
String head = "hello ";
String body = "worldrn ";
Out. write (head. getBytes ());
Out. write (body. getBytes ());

We sent hello. When hello didn't receive ack confirmation (TCP is a reliable connection, and every data sent must receive an ack confirmation from the other party; otherwise, it will be re-sent, according to the Nagas algorithm, world will not be sent immediately and will wait until ack is confirmed (at most MS will be sent by the other party), or wait until TCP buffer content> = MSS, obviously, we have no chance to write data after we write the world, so we can only wait for the hello ack to send the world, unless we disable the nags algorithm, the data will be sent immediately.

Refer to: http://zh.wikipedia.org/wiki/%E7%B4%8D%E6%A0%BC%E7% AE %97%E6%B3%95


SoLinger

When we call socket. close () to return, the data written by the socket may not have been sent to the other party. For example

The code is as follows: Copy code

Socket socket = new Socket ();
Socket. connect (new InetSocketAddress (host, 8000 ));
InputStream in = socket. getInputStream ();
OutputStream out = socket. getOutputStream ();
String head = "hello ";
String body = "worldrn ";
Out. write (head. getBytes ());
Out. write (body. getBytes ());
Socket. close ();

When socket. close () is called here to return, hello and world may not have been successfully sent to the other party. If we set the linger and not less than 0, for example:

The code is as follows: Copy code

Bool on = true;
Int lineger = 100;
....
Socket. setSoLinger (boolean on, int linger)
......
Socket. close ();

Copy code

 

Then close will not be returned until the sent data has been confirmed. However, if the other party goes down and times out, the response will be returned based on the time set by the linger.


UrgentData and OOBInline

TCP emergency pointers are generally not recommended, and different TCP/IP implementations are also different, generally, if you have urgent data, you would rather establish a new TCP/IP connection to send data, so that the other party can handle it urgently.

You can ignore these two parameters. If you want to know more, check the information yourself.

SoTimeout

Set the timeout time for the socket to call InputStream to read data, in milliseconds. If this time is exceeded, java.net. SocketTimeoutException will be thrown.

 

KeepAlive

Keepalive is not a common TCP connection. When we connect to a client as a server, if keeplive is set to true, when the other party does not send any data, if the time exceeds one (depending on the system kernel parameter configuration), an ack detection packet will be sent to the other party to check whether the TCP/IP connection between the two parties is valid (the other party may break the network ), in Linux, it seems that the time is 75 seconds. If this parameter is not set, when the client goes down, the server will never know that the client is down and will still save the invalid connection.

SendBufferSize and ReceiveBufferSize

The default value is 8192 in the TCP sending cache and receiving cache, which is usually enough. Even if you add the sending cache, the recipient does not add the corresponding receiving buffer, in the TCP three-way handshake, the final maximum sending window is the smallest buffer zone of both parties. Even if you ignore it and send more data, the extra data will be discarded. Unless both parties negotiate.

 

Related Article

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.