1 Introduction
socket network programming, can specify a different communication protocol, here we use the TCP protocol a java-based C / S mode "hello / hi" Internet chat program
2. Objectives
1). Chat program through the network, to understand the basic usage java Socket API interface
2). Java Socket API overview
3). Linux socket API simple analysis
4) The connection and protocol termination tcp
5). Explore the relationship between java socket API and linux socket api
3. linux socket API simple analysis
1). Tcp brief overview of the agreement
tcp byte stream transport protocol layer provides a reliable connection-oriented protocol services, it will generate a packed user data segment sent, a timer is simultaneously started; receiving terminal will verify the data simultaneously, data rearrangement disorder and discards the duplicate data.
tcp connection-oriented, meaning that each data transmission connection is established between the first ends; should close the connection to terminate transmitting of
a). to establish a connection
Client: a request sender; server: a data receiver
tcp three-way handshake to establish a connection through
The client first sends a message segment, active open -> server sends back a SYN segment as a response -> client then sends a reply to the server to confirm a segment
b). terminate the connection
tcp need four-way handshake to close the connection, because full-duplex tcp connections have closed in both directions, and each will need to confirm the closure, thereby requiring a four-way handshake
2). API analysis
a). the establishment and termination
Client calls the connect () method when will conduct three-way handshake to establish a connection, the connection is established only when the failure / will return
Prior to this, the server will always be blocked waiting for the client's request
When the connection is established, the client and server for data transmission
After the transfer, the client calls the close () method,
b). bind
It will be given to a local protocol address of the socket
c). listen
When the server calls socket (), it assumes that this is an active connection (about to connect calls originating client socket connection), and listen () then it is converted to a passive connection, the kernel receives points to the socket connection request
The kernel maintains two queues: queue not complete the connection has been completed connection queue
d). accept
When clients connect, and creates an entry in the connection queue is not completed on the server side, the time when the connection is completed, move the entry to the connection queue has been completed
accept the connection has been completed from the queue to get a connection has been completed
4. Based on the java simple "hello / hi" network chat program
. 1 Import the java.io. * ; 2 Import the java.net.ServerSocket; . 3 Import the java.net.Socket; . 4 . 5 public class Server { . 6 public static void main (String [] args) throws Exception { . 7 System.out.println ( "the server starts, .... waiting for connection" ); 8 // 1. Create ServerSocket object, bound port, start waiting for a connection . 9 ServerSocket Server = new new ServerSocket (6666 ); 10 // 2. The method of receiving a connection accept return socket object; this method blocks until an incoming connection, returns the new socket 11 Socket = the Socket server.accept (); 12 is // 3. takes an input stream 13 is the InputStream IS = Socket.getInputStream (); 14 // 4. one-time data read 15 byte [] B = new new byte [1024 ]; 16 int len = is.read (B); . 17 // parse array 18 is String MSG = new new String (B, 0 , len); . 19 System.out.println ( "the From Client->" + MSG); 20 is 21 is // 5. obtain the output stream to write data to the client 22 is the OutputStream OUT = socket.getOutputStream(); 23 out.write("Hi".getBytes()); 24 // 关闭资源 25 out.close(); 26 is.close(); 27 server.close(); 28 } 29 }
. 1 Import the java.io. * ; 2 Import the java.net.Socket; . 3 . 4 public class Client { . 5 public static void main (String [] args) throws Exception { . 6 System.out.println ( "clients transmit data" ) ; 7 // 1. Create Socket, determines where to connect to . 8 the Socket Client = new new the Socket ( "localhost", 6666 ); . 9 // 2. obtain an output stream 10 the OutputStream OS = client.getOutputStream (); . 11 // . 3. write data 12 os.write ( "the Hello" .getBytes ()); 13 is // 4. acquired input stream, acquires information returned from the server 14 the InputStream in = client.getInputStream (); 15 16 // 5. The reading returned from the server data . 17 byte [] B = new new byte [100 ]; 18 is int len = in.read (B); . 19 System.out.println ( "the From Sever->" + new new String (B, 0 , len)); 20 is // Close the resource 21 is in.close (); 22 is os.close (); 23 is client.close (); 24 } 25 }
5. java socket API relations between them and linux socket api
By the above procedure, we can observe the java server side compared to the less linux bind () and listen () method two, the client can not connect () method
We look at Java and Linux Sever-side API correspondence, the following is a map of the Internet, network sources ( https://blog.csdn.net/vipshop_fin_dev/article/details/102966081 )
When running on a linux system time, jvm linux underlying calls socket () function, we compare the corresponding server-side API
. A ServerSocket server = new ServerSocket (6666); will create a socket, while the bottom layer (corresponding linux api) is to achieve the following three processes:
1. Create a socket
To perform network I / O, we must first call the process a socket function, and will specify a desired protocol type and socket type
When successful socket function returns a small non-negative integer, because everything is a file in Linux, so this represents an integer file descriptor
At this creates a socket corresponding structure and mapped it and a file has been opened
2. The socket and the corresponding local protocol address corresponding to (bind function)
For TCP protocol, bind and may be a function and an IP port binding; in this case the socket state TCP_CLOSE
If you do not bind the port number, the kernel will bind socket for a temporary port
If you do not bind the IP address for the server, the kernel will send client SYN destination IP address as the source IP address of the server
3. listen () listen
Can be known from the above, the listen will be active into passive connection, the socket will be converted from closed state to state linsten; and maintains two queues
此时会和客户端进行三次握手来建立连接
b. Socket socket = server.accept();
linux中由TCP服务器调用,从已完成的连接队列的队头返回下一个已完成连接;成功则会返回由内核创建的新的描述符;
在并发服务器中,accept()返回后,服务器会调用fork函数,创建一个子进程,由该子进程来和客户端进行通讯,此时套接口对应文件描述符的引用计数会增加
同时父进程会关闭该已连接套接字,即会将引用计数减少。然后在原有的监听套接口上,继续监听有无其他连接,当由连接的时候,再次accept处理连接
c. server.close();
当待关闭的socket的描述符的引用计数为0的时候才会真正的关闭连接
参考来源:
1. https://blog.csdn.net/vipshop_fin_dev/article/details/102966081
2. 《UNIX网络编程》