TCP/IP Protocol Family 17 application layer Introduction socket demo and packet capture analysis

Source: Internet
Author: User
Tags ack bind connect socket flush readline socket port number
First Order

The author introduces the client-server paradigm, the interface of socket sockets and common functions, and then enumerates the demo of UDP and TCP respectively.

This chapter about the next, the demo is a c example, the previous document introduced the UDP demo.

So here's a demo of TCP. Two socket keyword

Socket Communication steps: (simple 4 steps)

1. Set up server ServerSocket and client sockets

2. Open the output input stream connected to the socket

3. Read and write operations in accordance with the Protocol

4. Close the corresponding resource- related APIs
class ServerSocket

This class implements a server socket. The server socket waits for the request to pass through the network. It performs certain actions based on the request, and may then return the results to the requestor.

The actual work of the server socket is performed by an instance of the SocketImpl class. The application can change the socket factory that creates the socket implementation to configure itself, creating a socket that is appropriate for the local firewall.

Some important methods: (see the official API bar for specific people)

ServerSocket (int port, int backlog)
Creates a server socket with the specified backlog and binds it to the specified local port number.

Bind (socketaddress endpoint, int backlog)
Bind the ServerSocket to a specific address (IP address and port number).

Accept ()
Listen for and accept connections to this socket

Getinetaddress ()
Returns the local address of this server socket.

Close ()
Close the socket. class Socket

This class implements a client socket (which can also be called a "socket"). Sockets are the endpoints of communication between two machines.

The actual work of the socket is performed by an instance of the SocketImpl class. The application can configure itself to create a socket that is appropriate for the local firewall by changing the socket factory that created the socket implementation.

Some important methods: (see the official API bar for specific people)

Socket (inetaddress address, int port)
Creates a stream socket and connects it to the specified port number for the specified IP address.

Getinetaddress ()
Returns the address of the socket connection.

Shutdowninput ()
The input stream for this socket is placed at the end of the stream.

Shutdownoutput ()
Disables the output stream for this socket.

Close ()
Close the socket. Demo

Server

Import java.io.IOException;
Import java.net.InetAddress;
Import Java.net.ServerSocket;

Import Java.net.Socket; public class TCPServer {public static void main (string[] args) {try {//1. Create a server-side socket, which is serve
	            Rsocket, specify the port to bind, and listen for this port serversocket serversocket=new serversocket (8888);
	            Socket Socket=null;
	            Log the number of clients int count=0;
	            SYSTEM.OUT.PRINTLN ("* * * server is about to start, waiting for client connections * * *"); Loop listener waits for the client to connect while (TRUE) {//calls the Accept () method to start listening, waiting for the client to connect Socket=serversocket
	                . Accept ();
	                Create a new thread Serverthread serverthread=new serverthread (socket);

	                Start thread Serverthread.start ();
	                The number of count++;//statistics clients System.out.println ("Number of clients:" +count);
	                InetAddress address=socket.getinetaddress ();
	   System.out.println ("IP of Current client:" +address.gethostaddress ());         }} catch (IOException e) {e.printstacktrace (); }
	    }
}
Thread

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;

Import Java.net.Socket;

    public class Serverthread extends thread {//and the socket socket socket associated with this thread = NULL;
    Public serverthread (socket socket) {this.socket = socket;
        }//The operation that the thread performs, responding to a request from the client public void run () {InputStream is=null;
        InputStreamReader Isr=null;
        BufferedReader Br=null;
        OutputStream Os=null;
        PrintWriter Pw=null;
            try {//Get input stream and read client information is = Socket.getinputstream ();
            ISR = new InputStreamReader (IS);
            br = new BufferedReader (ISR);
             String temp = null;
             String info = "";
                 while ((temp = br.readline ()) = null) {info + = temp;
                 SYSTEM.OUT.PRINTLN ("Client connection received"); SYSTEM.OUT.PRINTLN ("Server received client information:" + info+ ", current client IP is:" + socket.getinetaddress (). gethostaddress ());
            } socket.shutdowninput ();//Close input stream//Get output stream, respond to client's request OS = Socket.getoutputstream ();
            PW = new PrintWriter (OS);
            Pw.write ("Hello" +info);
            Pw.flush ();//Call Flush () method to buffer output} catch (IOException e) {//TODO auto-generated catch block
        E.printstacktrace ();
                }finally{//Close resource try {if (pw!=null) pw.close ();
                if (os!=null) os.close ();
                if (br!=null) br.close ();
                if (isr!=null) isr.close ();
                if (is!=null) is.close ();
            if (socket!=null) socket.close ();
            } catch (IOException e) {e.printstacktrace (); }
        }
    }
}

Client

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
Import Java.net.Socket;

Import java.net.UnknownHostException; public class TCPClient {public static void main (string[] args) {try {//1. Create client socket, specify server address and end
	            Port socket socket=new socket ("127.0.0.1", 8888);
	            2. Get the output stream, send the message to the server OutputStream outputstream=socket.getoutputstream ();//get an output stream to send information to the service side
	            PrintWriter printwriter=new PrintWriter (outputstream);//The output stream is packaged into a print stream user User=new user ("admin", "123456");
	            Printwriter.print (User.tostring ());	           
	            Printwriter.flush ();
	            Socket.shutdownoutput ();//Turn off the output stream//3. Gets the input stream and reads the server-side response information InputStream is=socket.getinputstream ();
	            BufferedReader br=new BufferedReader (New InputStreamReader (IS));String Info=null;
	            while ((Info=br.readline ())!=null) {System.out.println ("I am the client, server says:" +info);
	            }//4. Close resource Br.close ();
	            Is.close ();	     
	            Printwriter.close ();
	        Socket.close ();
	        } catch (Unknownhostexception e) {e.printstacktrace ();
	        } catch (IOException e) {e.printstacktrace (); }
	    }
	
}
There's another user who won't stick it out.

Service-Side output:



Client output:

I am the client, the server says Hello User [Name=admin, password=123456]

Grab Bag


Inside the red box is an interactive process.

This process we see 121-123 is 3 times handshake to establish the connection.

124 is the PSH client sends data to the server

126 is the ACK returned by the server.

125 starts with a 4-time wave break link. 125 the client sends Fin. Seq=35

127 is PSH with ACK. Where PSH is the server King Client push data, ACK is confirmed 125,ack=36

128 is the server sending fin,seq=41,ack=36

129 is the client ACK. Seq=36,ack=42

can be combined with diagrams to understand

And look at the head data for the packet.


The front is the frame header, IP header, the front of the UDP is introduced, it will not be expanded. The following includes the TCP header and data.

Because the TCP header has a fixed length of 20 bytes, the variable length is 40 bytes, mainly during the link establishment phase. So look at the TCP header data again.



Source port number: 52173, corresponding CBCD

Destination port number: 8888, corresponds to B8

Serial number seq: in the process of transmitting data, assign a sequence number to each packet to ensure the sequence of the data transmitted by the network AD 3a 01 26

Confirmation Number ACK: used to confirm the receipt of the relevant packet, the content is expected to receive the next message serial number, to solve the problem of packet loss 00 00 00 00

Header Length: 8

Flag bit: This section mainly flags the properties of the packet, where SYN is request synchronization. 02

Window Size: function: Congestion flow control: 8192 corresponds to 2000

Checksum: 3f70

Emergency pointers: You can tell the emergency data location, 0

Here are the options:

Maximum message transmission segment (Maximum Segment Size---MSS)

1460

MSS is the most frequent and earliest option in the TCP option. MSS option occupies 4byte. MSS is the maximum length of the data field in each TCP message segment, note: Only the data part of the field, not including the head of TCP. TCP in three handshake, each party will announce its expected to receive the MSS (MSS only appear in the SYN packet) if one side does not accept the other side of the MSS value is positioned the default value of 536byte. MSS values are too small or too large to be inappropriate. Too small, for example, MSS value is only 1byte, then in order to transmit this 1byte data, it consumes at least 20 bytes IP header + 20 byte TCP head =40byte, this does not include the overhead of the second layer head, obviously this data transmission efficiency is very low. MSS is too large, so that the packet can be encapsulated very large, then the probability of fragmentation in the IP transmission will increase, the receiver in the processing of fragmented packets consumed by the resources and processing time will increase, if the Shard in the transmission also occurred retransmission, then its network overhead will increase. Therefore, a reasonable MSS is crucial. The reasonable value of MSS should be the maximum value to ensure that the packet is not fragmented. For Ethernet MSS can reach 1460byte.

IP has a similar concept of MTU


Mtu=mss+tcp Header+ip Header.

Window size

Windows Scaling accounts for 3 byte, where one byte represents the shift value s. The new window value equals the number of window bits in the TCP header increased from 16 to (16+s). This is equivalent to moving the window value to the left of the S bit to get the actual window size. The maximum allowable value for the shift value is 14, which is equivalent to a maximum window size of 65535*2^14 or 1GB.

Here is 2, meaning to enlarge 4 times times.

sack:permited

Select confirm.

NOP NOP (no operation). This field is designed primarily to provide a filler gasket. The head of TCP must be a multiple of 4byte, but most TCP options are not multiples of 4byte. If the entire TCP Options section is not a multiple of 4byte, then it is necessary to populate it with 1 or more bytes of meaningless NOP to conform to the provisions of the TCP header construction. And the fill between options.

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.