TCP - Transmission Control Protocol

A, TCP is a service provided by the application layer

TCP protocol: transfer control protocol connection-oriented, reliable byte stream transport layer based on a protocol

Features:

  • Connection-oriented
  • Point to point communication
  • High reliability
  • System resources, low efficiency

  TCP is a connection-oriented applications (usually the Server and Client) means that both use, you must first establish a TCP connection before exchanging data with each other;

  TCP to provide reliability in the following ways:

  • Application data is divided into TCP deemed most appropriate for the transmission of the data block (data length of the UDP packet is generated by the application remain unchanged), delivered by TCP to IP information unit called a segment or segments (segment);
  • When TCP sends a segment, it starts a timer, waiting for the destination to acknowledge the receipt of this segment, if not timely receipt of this confirmation, will re-send the message segment;
  • When the TCP data received from the other end of the connection, it will send an acknowledgment after a delayed fraction of a second;
  • TCP header and the holding portion and it checks the message segment, then a test end to end and the aim of detecting any change in the data transmission process, if the received message segment has an error checksum, TCP discards this segment, and does not reply to the confirmation (desired timeout and retransmits the transmission side);
  • TCP segment as the IP datagram transmission, to reach the IP datagram may be out of order, so arriving TCP segments may also be out of order, when necessary, TCP will reorder the received data Thereafter, in the right order to the application layer;
  • IP datagrams repetition occurs, the receiving TCP must discard duplicate data
  • TCP flow control may be provided, each side of the TCP connection has a fixed size of buffer space, the receiving TCP only allows the transmitting side can transmit and receive data buffer size of the receiving terminal, thus preventing the host so that faster slower host buffer overflow.

  Two applications exchanging connection via TCP byte stream consisting of 8bit bytes, TCP byte stream is no longer inserted recording identifier, called a byte stream service these (byte stream service), if one of the first application pass 10 bytes, and 20 byte transfer, re-transmission of 50 bytes, the receiving party can not understand the transmitting side the number of bytes for each transmission, the receiving side can receive these four parts of 80 bytes, each byte received 20 , exiled to the end of the byte TCP connection, the same byte stream and the other end of the TCP connection occurs.

  The content of TCP byte streams without any explanation, do not know the TCP byte stream data transmission what type of data, the interpretation of the byte stream from the TCP application layer both connected explained. This approach is very similar to the Unix operating system's handling of the byte stream files, Unix kernel for the content of an application to read and write without any explanation, but to the application process for the Unix kernel, it We can not distinguish which is a binary file or a text file.

Second, the interpretation of the TCP header and various fields

Here Insert Picture Description
TCP data is encapsulated in an IP datagram;
Excluding options and padding fields, typically TCP header has a fixed length of 20 bytes, but up to 60 bytes in length;

TCP header information field Interpretation:

  • Source port number and destination port number
      occupies 2 bytes, the transport layer port is a service interface and the application layer, used to find the transmitting end and the receiving end of the process, in general, and through the two port numbers of the IP header source IP address, destination IP address can uniquely identify a TCP connection in network programming, an IP address and a port generally referred to a socket interface, an interface port number and IP address (including the client, the server port number and IP address) can uniquely identify both the Internet each TCP connection;
  • Number
      occupies 4 bytes, used to identify the transmitting end receives a stream of data bytes sent to the TCP terminal, it indicates the first data byte in this segment from the TCP;
  • The acknowledgment number
      occupies 4 bytes, each byte transferred will be counted, then the acknowledgment sequence number comprises sending an acknowledgment of the end of the next expected sequence number received , and therefore, should be the last acknowledgment sequence number have been successfully received data byte sequence number plus 1, but only the acknowledgment field is valid when the ACK is identified as 1;
  • Offset data
      four bits, for indicating the TCP header length, if the option exists, then the default value is 20 bytes, and the maximum value of the offset data is 60 bytes;
  • Reserved field
      accounted for 6, can be temporarily ignored, 0s;
  • Flag (each one)
    • The URG (urgent): show Urgent Pointer field significant to 1;
    • ACK (acknowledgment): 1 indicates that when the acknowledgment number field is valid;
    • PSH (Push): The receiver shall to this segment as soon as the application layer is 1;
    • RST (Reset): 1 indicates that a TCP connection is faulty connections to be rebuilt;
    • SYN (Synchronize): a sequence number used to synchronize the connection establishment for establishing a connection;
    • The FIN (termination): 1 indicates that when the transmitting side data transmission is completed to release the connection requirements;
  • Receive window
      2 bytes, used for flow control and congestion control, 16bit field indicates the current size of the receive buffer, so that the maximum window size is 65535 bytes, but the new window scaling options allow the value to provide a more proportional change large window;
      in a computer network, typically the size of a reception capability of the receiver to control the transmission amount of data transmission side, one end of TCP connection is determined according to the value of their reception window buffer size, telling the sender, so that the other can determining the number of bytes of data transmitted;
  • Checksum
      2 bytes, covering the entire TCP segment, comprising a header portion and a data portion two, is a mandatory field, it must be calculated and stored by the sender, for verification by the receiver, the TCP checksum UDP checksum calculating the similarity is calculated using a pseudo-header;
  • Urgent pointer
      urgent pointer is an offset value and adding the sequence number field identifies the sequence number of the last byte of urgent data, TCP urgent mode is a way of sending end to the receiving end of the urgent data;

  The data in TCP segment part is optional, because when establishing a connection or terminate the connection, the two sides exchanged segment only TCP header, if one has no data to send, use no headers to confirm any data received data, when the timeout process will mostly without any transmission of data segments;

to sum up:

  The TCP user segment constituting a book package, it starts a timer after sending the data, the other end of the received data confirmed the data of the out of sequence reordering, discarding duplicate data, TCP provides end to end flow control, and and calculate a verification test and end mandatory.

  TCP is a connection-oriented protocol, no matter which party to another must be sent to establish a connection between the two sides before the data is now;

Third, the network is based on C / S model client (Client) and server (Server) in the TCP interactive step

Here Insert Picture Description

Four, TCP protocol programming exercises

Note: The client connects the server, you must first start the server;

  • Server
public static void main(String[] args) throws IOException {
        //创建serversocket的实例
        ServerSocket serverSocket = new ServerSocket();

        //绑定端口
        serverSocket.bind(new InetSocketAddress(8888));
//        System.out.println("服务端启动了");
        //监听并获得socket,该方法会阻塞
        Socket socket = serverSocket.accept();
//        System.out.println(socket.getRemoteSocketAddress()+" 客户端连接上了");
        
        //可以进行读写操作
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        String msg = null;
        while ((msg = reader.readLine())!= null) {
            System.out.println(msg);
        }

        //关闭资源
        reader.close();
        socket.close();
        serverSocket.close();
    }
  • Client
public static void main(String[] args) throws IOException {
        //创建socket实例
        Socket socket = new Socket();

        //连接服务器  192.168.31.135
        socket.connect(new InetSocketAddress("127.0.0.1", 8888));
//        System.out.println("客户端连接上服务器了");

        //发送消息
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello\n".getBytes());

        //关闭资源
        socket.close();
    }    

Fifth, to distinguish Socket programming based on TCP and UDP protocols
Based on Socket Programming TCP protocol Socket programming based on UDP protocol
The two sides need to establish a communication connection Communicating parties without establishing a connection
The two sides primary or secondary connection is established Communication both full equality

Streaming services : data is a data source, there is no limit of data transmission times and reception times is not directly related,
     the receiver in the data buffer, a data can not be received completely, the buffer can be placed, secondary read;
datagram service : transmission times and reception times are equal,
      if a receiving end fails to complete the read data transport layer, the remaining data is discarded directly.

Guess you like

Origin blog.csdn.net/Daria_/article/details/90704793