Analysis and tools to achieve based on the underlying principle of JAVA Socket

Foreword

 Before work began, we first look at Socket

  The Socket called, also known as a socket, which is an abstraction layer, is simply present in different platforms (OS) common interface. Students learned network it can be understood based on the transport layer TCP / IP protocol into

Packaging step, we use the package to the upper surface so as to stream the same file open, close, and write operations. Moreover, it is for an application, the application may be transmitted through it to receive data or not used

Taking into account the number of network protocols.

 So, Socket is present in the different platforms of public interface is what does that mean?  

  The image of that is the "socket" is a convention or a way of communication between different OS. Socket By this convention, a computer may receive data from other computers, may be transmitted to other computers

data. Socket typical application is the Web server and browser, the browser obtains the URL entered by the user, by parsing out the IP address of the server and send a request to the server IP, server analyzes the received URL,

The contents of the corresponding page returned to the browser, the browser then parsed and rendered, will be text, pictures, video and other elements to the user.

 Problem again, it can not be by Socket communication between system?

  First, we look at commonly used operating system in the Socket.

  In the UNIX / Linux systems, in order to unify the hardware operation, simplify the interface, different hardware devices are viewed as a file. Operation of these documents, is equivalent to the operation of an ordinary file on disk.

You may listen to many experts say, UNIX / Linux file of everything! The guy was right.

  The students learned operating system may know, when the file I / O operation, the system will typically assign an ID document, which is the file descriptor. Simply put, it is the operating system for the conversion of documents for the file descriptor

The operation, which may be behind a normal file on the hard disk, FIFO, pipeline, terminal, keyboard, monitor, or even a network connection.

  Similarly, the network connection may also be defined as a similar I / O operations, similar to a file, it also has a file descriptor.

  So we can be performed when one communication by Socket, may also be referred to as a network file operation. When the network is established, socket () return value is the file descriptor. With this file descriptor, we can use common file manipulation functions to transmit data, for example:

  • Coming from a remote computer to read data Read ();
  • A write () to write data to the remote computer.

  Not difficult to find, in addition to the establishment of Socket process between different hosts unclear, Socket communication process is simple document workflow processes.

  On Windows systems, it has a similar "file descriptor" concept, but often referred to as "file handle." Therefore, this tutorial if it involves Windows platform will use the "handle", if it involves the use of the Linux platform

"Descriptor". And UNIX / Linux is different, Windows will distinguish between socket and file, Windows put the socket connection is treated as a network, it is necessary to call a special socket designed for the number of

According to the transfer function for input and output functions common file it is invalid.

 Come to the question

  Having said that, in the end Socket different definitions of communication between different systems is how it?

  In this, our relationship with Linux Socket JAVA Socket analysis as an example. First, take TCP Socket communication process is concerned, it is that the client and server TCP data exchange, it is divided into about several steps:

  1. Resource allocation system, the server Socket open process, listens to a specific port number
  2. Client to connect a specific port for the server IP
  3. Connection is established, start communication
  4. Communication is completed, the connection is closed

  Specifically, JAVA is how to complete a call to the underlying Linux Socket Interface of it? The following diagram, for example, when we create a TCP connection JAVA, JAVA need to instantiate the ServerSocket class, which encapsulates the underlying socket () method, the bind () method, the listen () method.

  

Wherein, socket () method is invoked JVM for Linux API detailed as follows:

    1 Create a socket structure
    2 Create tcp_sock structure, just finished creating state tcp_sock is: TCP_CLOSE
    3 and the socket is bound to create a file descriptor

  bind () method below in detail in the underlying Linux:

    1. The current network namespace name and port saved to bhash ()

    Can be understood as bound to the local system can be found.

  listen () method below in detail in the underlying Linux:

    1. Check whether there bhash the listening port
    2. Initialize csk_accept_queue
    3. The tcp_sock listening_hash pointer table stored in
    simple terms is verified whether the connection request port is opened.

  accpet () method below in detail in the underlying Linux:  

1. Call the accept method
2. Create a socket (preparation for creating a new connection to the client socket)
3. create a file descriptor
4. blocking wait (csk_accept_queue) Gets sock
We know listen stage, will be initialized to the listening sock csk_accept_queue, the queue is empty at this time, the accept () method in this case will stay blocked until the client behind the successful handshake, this queue only sock. csk_accept_queue If not empty, a sock is returned. subsequent logic shown, which accept as a second step following FIG:
5. remove the sock
6.socket sock with interrelated
7.socket associated with the file descriptor
8. return to the thread socket

  This, JAVA Linux API calls to complete the initial steps.

Server-side code:

 1 package tcp_network;
 2 
 3 import java.io.DataInputStream;
 4 import java.io.DataOutputStream;
 5 import java.io.IOException;
 6 import java.net.ServerSocket;
 7 import java.net.Socket;
 8 
 9 public class Tcp_server {
10     public static void main(String arg[]) throws IOException {
11         System.out.print("服务端启动.......\n");
12         ServerSocket server = new ServerSocket(9660);
13         boolean isRunable = true;
14         while (isRunable){
15             Socket client = server.accept();
16             System.out.print("一个客户端建立了连接.......\n");
17             new Thread(new Channel(client)).start();
18         }
19         server.close();
20     }
21     public static class Channel implements Runnable{
22         private Socket client;
23         private DataInputStream in_data;
24         private DataOutputStream out_data;
25         public Channel(Socket client) throws IOException {
26             this.client = client;
27             in_data = new DataInputStream(client.getInputStream());
28             out_data = new DataOutputStream(client.getOutputStream());
29         }
30         public String receive() throws IOException {
31             String data = in_data.readUTF();
32             return  data;
33         }
34         public void send(String msg) throws IOException {
35             out_data.writeUTF(msg);
36             out_data.flush();
37         }
38         public void release() throws IOException {
39             in_data.close();
40             out_data.close();
41             client.close();
42         }
43         @Override
44         public void run() {
45             try {
46                 String receive_data;
47                 while (true){
48                     receive_data = receive();
49                     if(!receive_data.equals(""))
50                     {
51                         if(receive_data.equals("Hello"))
52                         {
53                             System.out.print("IP:"+client.getInetAddress()+" 客户端信息:"+receive_data+"\n");
54                             send("Hi");
55                         }
56                         else {
57                             System.out.print("IP:"+client.getInetAddress()+" 客户端信息:"+receive_data+"\n");
58                             send(receive_data.toUpperCase());
59                         }
60                     }
61                 }
62             } catch (IOException e) {
63                 try {
64                     release();
65                 } catch (IOException ex) {
66                     ex.printStackTrace();
67                 }
68                 e.printStackTrace();
69             }
70         }
71     }
72 }

Client-side code:

package tcp_network;

import java.io.*;
import java.net.Socket;

public class Tcp_client {
    public static void main(String arg[]) throws IOException {
        Socket client = new Socket("localhost",9660);
        boolean isRuning = true;
        while (isRuning) {
            //new Send(client).send();
            //new Receive(client).receive();
            new Thread(new Send(client)).start();
            new Thread(new Receive(client)).start();
        }
    }
    public static class Send implements Runnable
    {
        private DataOutputStream out_data;
        private BufferedReader console;
        private String msg;
        public Send(Socket client) throws IOException {
            this.console = new BufferedReader(new InputStreamReader(System.in));
            this.msg = init();
            try {
                this.out_data = new DataOutputStream(client.getOutputStream());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        private String init() throws IOException {
            String msg=console.readLine();
            return msg;
        }
        @Override
        public void run() {
            try {
                out_data.writeUTF(msg);
                out_data.flush();
                System.out.println("send date !");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    public static class Receive implements Runnable{
        private DataInputStream in_data;
        private String msg;
        public Receive(Socket client){
            try{
                in_data = new DataInputStream(client.getInputStream());

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void run() {
            String data = null;
            try {
                data = in_data.readUTF();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.print("服务端:"+data+"\n");
        }
    }

}

 

 

 

 

 

 

reference:

  https://blog.csdn.net/vipshop_fin_dev/article/details/102966081

  http://c.biancheng.net/view/2128.html

 

 

Guess you like

Origin www.cnblogs.com/xshun/p/11991482.html