1, check the statistics of the network:
Netstat-s Results Display Statistics, protect the delivery package, establish the number of connections
Netstat-at List all TCP ports
Netstat-au List all UDP ports
Netstat-aut currently running the TCP/UDP service
The parameters commonly used in Netstat are as follows:
-S or –statistice displays the statistics of network work information.
-T or –tcp shows the connection status of the TCP transport protocol.
-U or –UDP shows the connection status of the UDP transport protocol.
-A or –all displays the sockets in all connections.
-N or –numeric uses the IP address directly, not through the domain name server.
Netstat-n | awk '/^tcp/{++s[$NF]} end{for (A in S) print A, s[a]} '
$NF represents the penultimate parameter, and the result of a run is as follows:
Time_wait state can be converted from 3 states, according to the TCP protocol defined by the 3 handshake disconnection rules, the initiation of the socket active closed socket will enter the TIME_WAIT state. The TIME_WAIT state will last 2 MSL (Max Segment Lifetime), and the default is 4 minutes, or 240 seconds, under Windows. The socket in the TIME_WAIT state cannot be reused. The specific phenomenon is for a server processing a large number of short connections, if the server actively shut down the client connection, will result in a large number of servers in the TIME_WAIT state of the socket, or even more than the socket in the established state, Severely affects the processing power of the server and even exhausts the available sockets to stop the service.
Some optimizations can be made by debugging the Linux kernel parameters:
(1) net.ipv4.tcp_fin_timeout, default 60s, decrease fin_timeout, reduce the number of time_wait connections.
(2) Net.ipv4.tcp_tw_reuse = 1 means turn on reuse. Allows time-wait sockets to be re-used for new TCP connections, which defaults to 0, which means shutdown;
(3) Net.ipv4.tcp_tw_recycle = 1 means to turn on fast recycling of time-wait sockets in TCP connections, which defaults to 0, which means shutdown.
2. TCP (Transmission Control Protocol) Three handshake and four breakup
TCP provides an abstraction of reliable transmission on unreliable transmission channels, hiding most of the complexity of our applications: Packet retransmission, sequential delivery, congestion control and avoidance, data integrity, and other features. When you use a TCP stream, the TCP protocol guarantees that all of your bytes are sent in the same way as the received data, and they reach the peer in the same order. TCP is designed to send protocols in a sequential order, rather than a timed send protocol.
The so-called three-time handshake (three-way handshake) means that when a TCP connection is established, the client and server are required to send a total of 3 packets. The purpose of the three-time handshake is toconnect the server to specify a port, establish a TCP connection, and synchronize the serial number and confirmation number of both parties and Exchange TCP window size informationIn socket programming, when the client executes connect (), three handshakes are triggered.
Because TCP connections are full-duplex, each direction must be closed separately. The principle is that when a party completes its data sending task, it can send a fin to terminate the connection in this direction. Receiving a fin only means there is no data flow in this direction, and a TCP connection can still send data after receiving a fin. The first party to close will perform an active shutdown, while the other side performs a passive shutdown.
The connection to the TCP protocol is a full-duplex connection, and a TCP connection has a bidirectional read-write channel.
In short, "First shut down, then write", there is a total of four stages. Take a client-initiated shutdown connection as an example:
1. Server Read Channel shutdown
2. Client Write channel shutdown
3. Client Read channel shutdown
4. Server Write channel shutdown
The shutdown behavior is to send a fin (finish) data segment to the sender after the initiator data has been sent. Until you receive the fin sent by the other party, and the other party receives the acknowledgement ACK, the data communication between the two sides is completely terminated, and each receive in the process needs to return the acknowledgment segment ack.
Detailed process:
First Stage
(1) After the client sends out the data, send a fin data segment to the server, the serial number is I;
(2) After the server receives fin (i), returns the acknowledgment segment ACK, the serial number is i+1, closes the server read channel;
(3) When the client receives an ACK (I+1), it shuts down the client write channel;
(At this point, the client can still read the server's data through the read channel, the server can still write data through the Write channel)
Phase II
(1) After the server sends out the data, sends a FIN data segment to the client, the serial number is J;
(2) After the client receives fin (j), it returns the acknowledgment segment ACK, the serial number is j+1, and the client read channel is closed;
(3) After the server receives an ACK (J+1), it shuts down the server write channel.
This is a standard TCP shutdown of two stages, and both the server and client can initiate shutdown, completely symmetric.
The green arrow is client, and the blue is server.
Reference: (1) http://www.cnblogs.com/Jessy/p/3535612.html (2) http://www.oschina.net/question/2011290_2199294?fromerr= O3YIYWOP (3) Http://itindex.net/detail/51010-httpclient-%E5%8E%9F%E7%90%86-%E6%97%B6%E5%BA%8F%E5%9B%BE
3. Traffic control and congestion control of TCP protocol
4. Java NIO
is a synchronous non-blocking I/O model and the basis for I/O multiplexing. Specifically, selector will constantly poll the channel registered on it, if a channel has a new TCP connection, read or write events, the channel is in a ready state, will be selector polling out, The Selectorkey can then be used to obtain a set of ready channel for subsequent I/O operations.
NIO single-threaded polling event to find a read-write network descriptor to read and write. In addition to polling for events that are blocked (nothing that can be done must be blocked), the remaining I/O operations are pure CPU operations, and there is no need to turn on multithreading.
And because of the thread savings, the number of connections due to the problem caused by thread switching is also solved, which provides the possibility to deal with massive connections.
The efficiency of single-threaded processing I/O is really very high, no thread switching, just desperately reading, writing, selecting events. But now the server, is generally multi-core processor, if can take advantage of multiple cores for I/O, there is no doubt that the efficiency will be improved.
public class Multiplexertimeserver implements Runnable {private Selector selector;private Serversocketchannel Servchannel;private volatile Boolean stop;/** * initializing multiplexer, binding listening port */public multiplexertimeserver (int port) {try {selector = Selector.open ();//channel is mainly used to read and write data on the network. Open Serversocketchannel, which listens to the client connection, which is the parent pipe of all client connections Servchannel = Serversocketchannel.open ();// Set to non-blocking mode servchannel.configureblocking (false);//Bind Listening Port 8080servchannel.socket (). bind (New inetsocketaddress (port), */* * Selector will continuously poll the channel on it, if a channel has a new TCP * connection access, read and write events, the channel is in a ready state * * Register to the REACOTR thread of the multiplexer selector, monitor the ACCEPT event */servchannel.register (selector, selectionkey.op_accept); System.out.println ("The time server is start in port:" + port);} catch (IOException e) {e.printstacktrace (); System.exit (1);}} public void Stop () {this.stop = true;} public void Run () {while (!stop) {try {//] This method performs a blocking selection operation.//It returns Least one channel is selected (only if there is at least an event ready)Return, so is blocked)//This selector ' s wakeup method is invoked, the current thread is interrupted,//or the given timeout period Expires, whichever comes first. Selector.select (1000); Block wait, sleep time is 1sset<selectionkey> Selectedkeys = Selector.selectedkeys (); */* when there is a channel in the Ready state, The selector will return the Selectionkey * collection of the channel for the Ready state, iterating through the channel set of the ready state, and can perform asynchronous read and write operations on the network */iterator<selectionkey> it = Selectedkeys.iterator (); Selectionkey key = Null;while (It.hasnext ()) {key = It.next (); It.remove (); try {//Event dispatcher, single-threaded select-Ready event. I/O processor, including connect, read, write, and so on, this pure CPU operation, generally turn on the CPU core threads can be. Business threads, after I/O is processed, the business usually has its own business logic, and some other blocking I/O, such as DB operations, RPC, etc. As long as there is blocking, a separate thread is required. Handleinput (key); So it is best to use other threads here instead of affecting the event dispatcher thread} catch (Exception e) {if (key! = null) {Key.cancel (); if (key.channel () = null) key.ch Annel (). Close ();}}} catch (Throwable t) {t.printstacktrace ();}} After the multiplexer is closed, all resources registered on the channel and pipe are automatically registered and closed, so there is no need to re-release the resource if (selector! = null) try {selector.close ();} catch ( IOException e) {e.printstacktrace ();}} Private void Handleinput (Selectionkey key) throws IOException {if (Key.isvalid ()) {//Handle new Access Request message if (Key.isacceptable ()) {//Accept A new Client access request Serversocketchannel SSC = (serversocketchannel) key.channel (); Socketchannel sc = ssc.accept ();//Set the client to be asynchronous non-blocking sc.configureblocking (false); ADD the new connection to the Selectorsc.register (selector, selectionkey.op_read);} if (key.isreadable ()) {/* * Read Data * Read the number of bytes, the return value has the following three results: * (1) greater than 0, read to byte, encode it * (2) equals 0, no read to Byte, South textile shares normal scene, ignore * (3)-1, Link is off Closed, need to close socketchannel, release resources */socketchannel sc = (socketchannel) key.channel (); Bytebuffer Readbuffer = bytebuffer.allocate (1024);//Because the Socketchannel is set to asynchronous non-blocking, its read is non-blocking int readbytes = Sc.read ( Readbuffer); if (Readbytes > 0) {/* * Sets the current limit of the buffer to position,position to 0 for subsequent read operations to the buffer. * Then create a byte array based on the number of bytes in the buffer, call the Get () operation to copy the buffer-readable number of bytes * Group into the newly created byte array */readbuffer.flip (); byte[] bytes = new byte[ Readbuffer.remaining ()];readbuffer.get (bytes); String BODY = new String (bytes, "UTF-8"); System.out.println ("The time server receive order: "+ body); String currenttime = "QUERY time ORDER". Equalsignorecase (body)? New Java.util.Date (System.currenttimemillis ()). ToString (): "Bad ORDER";d Owrite (SC, currenttime);} else if (Readbytes < 0) {//Peer link off key.cancel (); Sc.close ();} else{;//Read 0 bytes, ignoring}}}}private void Dowrite (Socketchannel ch Annel, String response) throws IOException {/* * Because the Socketchannel is asynchronous and non-blocking, and there is no guarantee to send all the data that needs to be sent at once, there will be a write half-packet problem. * Need to register write operation???, constantly polling selector will not send out the Bytebuffer sent complete. The Bytebuffer Hasremain () * method can be used to determine whether the send is complete. */if (response! = null && Response.trim (). Length () > 0) {//reply message is sent asynchronously to the client byte[] bytes = Response.getbytes (); Bytebuffer WriteBuffer = bytebuffer.allocate (bytes.length);//sends Byte data in buffer Writebuffer.put (bytes); Writebuffer.flip ( ); Buffer Reset Channel.write (WriteBuffer);}}}
Selector polling is blocked, while true I/O is asynchronous and non-blocking.
For NIO, the cache can use Directbytebuffer and Heapbytebuffer. If Directbytebuffer is used, it is generally possible to reduce the system space to a copy of the user space. However, the cost of creating and destroying the buffer is higher and more unsuitable for maintenance, which is commonly used when reading large files.
Reference article: http://blog.csdn.net/szzt_lingpeng/article/details/50612018
5. In NiO, if you do not explicitly callsystem.gc()What is the problem?
The GC rules for Directbuffer are the same as those for heap objects, and only garbage objects are recycled, and determining whether or not a garbage object is still based on the surviving nodes in the reference tree.
If the Directbytebuffer space is sufficient, then System.GC () will not trigger FULLGC. That is, when there is not enough space, the display call can be reclaimed, if not explicitly called, it can only be thrown memory exception.
In the garbage collection, although the virtual opportunity to directmemory recovery, but directmemory not like the new generation and the old age, the discovery of space is not enough to notify the collector to garbage collection, it can only wait for the old age full after fullgc, and then "by the Way" Help it clean out the discarded objects in memory. Otherwise, you can only wait until the memory overflow exception is thrown, and call System.GC () in the Catch block.
Reference: http://blog.csdn.net/donsonzhang/article/details/46666353
6, HTTPS working principle, and the difference between HTTP
For HTTPS, refer to: http://www.cnblogs.com/xinzhao/p/4949344.html
7. Describe the HTTP protocol (the format of HTTP request and response messages)
The HTTP protocol uses "request-answer" mode, when using normal mode (non-keepalive mode), each request/reply client and server to create a new connection, immediately after the completion of the disconnection (HTTP protocol is a non-connected protocol) When using Keep-alive mode (also known as persistent connection, connection reuse), the Keep-alive feature keeps the client-to-server connection active, and the keep-alive feature avoids establishing or re-establishing a connection when a subsequent request to the server occurs.
(1) In HTTP 1.0 keep-alive is turned off by default, you need to add "connection:keep-alive" to the HTTP header in order to enable keep-alive
(2) in HTTP 1.1, keep-alive is enabled by default, and adding "connection:close" can be turned off. Most browsers now use the HTTP 1.1 protocol, which means that the Keep-alive connection request is initiated by default, so whether a full keep-alive connection can be completed depends on the setting of the Web server.
1, Request line
Consists of 3 parts: The request method, the URL (see note 1), and the protocol version, separated by a space
The request method includes, PUT, POST, TRACE, OPTIONS, delete, and extension methods, not all of which are implemented by all servers, and some of which are not available for security purposes even if supported
The format of the protocol version is: http/major version number. Minor version number, commonly used with http/1.0 and http/1.1
2, request the head
The request header adds some additional information to the request message, consisting of a "name/value" pair, separated by a colon between the name and the value, with each row.
Common request headers are as follows:
|
Request Header |
Description |
|
Host |
The server address to accept the request, either IP: port number or domain name |
|
User-agent |
The application name that sent the request |
|
Connection |
Specify the properties associated with the connection, such as Connection:keep-alive |
|
Accept-charset |
Notifies the service side of the encoding format that can be sent |
|
Accept-encoding |
Notifies the server that a data compression format can be sent |
|
Accept-language |
Notifies the server which languages can be sent |
There is a blank line at the end of the request header, which means that the request header ends and the request body is next, which is important and essential
HTTP Response message Format:
The HTTP response message consists of a status line, a response header, and a 3 part of the response body.
1, status line
Consists of 3 parts, namely: protocol version, Status code, status code description, separated by a space. The common status codes are as follows:
|
Status code |
Description |
|
200
|
Successful response |
|
302 |
Jump, the jump address is specified by the Location property in the response header (the difference between forward and redirect in the JSP) |
|
400 |
Client requests have syntax errors and cannot be recognized by the server |
|
403 |
The server received the request but refused to provide the service (authentication failed) |
|
404 |
Request resource does not exist |
|
500 |
Server Internal Error |
2, Response head
Similar to the request header, additional information is added to the response message. Common response headers are as follows:
content-length
content-language
|
response header |
description |
|
server |
Server application software name and version |
|
Content-type |
Response body type (picture or binary string)
|
|
Response Body length |
|
Content-charset |
" Response body use encoding
|
|
content-encoding |
Response body use data compression format
|
TD valign= "Top" >
| Response body language
|
Java Interview 15| network