Home >Java >javaTutorial >Java network programming explained in detail with pictures and text

Java network programming explained in detail with pictures and text

黄舟
黄舟Original
2017-03-04 10:04:442753browse

This article introduces network-related theories and simple Java network programming examples

This article mainly introduces an overall architecture of a computer network and the functions of each layer effect.

  • The concept of computer network

  • OSI Reference Model

  • TCP/IP Reference Model

  • IP Protocol

  • TCP protocol and port

  • Java network programming introductory program


Computer The concept of network

A network is a thing that is interconnected between different nodes through connections. By analogy, a computer network is a powerful network system that connects computers in different geographical locations through communication lines. In this network, each computer is a node.

OSI Reference Model

OSI (Open System Interconnection) is a set of network architecture studied by the ISO organization. This name is good
The names and functions of each layer should be understood:

Name Function
Physical layer Don’t understand wrongly, this layer does not include the physical media of network cables and cables. Here we only specify the interface type, signal voltage, etc. of network cables and cables. Using bit transmission
Data link layer is responsible for the route between two adjacent nodes and is transmitted in frame units. Typical equipment switch (Switch)
Network layer Two computers may transmit data through many data links, and the role of the network layer is to choose the optimal route. A typical device is a router
Transport layer Provides the functions of establishing, maintaining and canceling transmission connections for sessions between two end systems. Use message transmission
Session layer Manage the session process between processes, that is, establish, manage, and terminate sessions between processes. Use message transmission
presentation layer to encrypt, decrypt, decompress and format data, etc.
Application layer This layer interacts with the user's specific application. For example: sending and receiving E-mail, etc.

TCP/IP Reference Model

Because the OSI network structure has too many layers and is too complex, the TCP/IP protocol has become unavailable Born. The TCP/IP protocol also relies on the layered idea of ​​​​OSI, but it is only divided into four layers:

Name Function
Host network layer Provide an access interface for the upper layer
Network interconnection layer Put IP data The packet is sent to the target host. This layer uses the IP protocol, which specifies the format of data packets and the process of finding routes for data packets.
Transport layer Enables processes on the source host and target host to conduct conversations. This layer defines two protocols, TCP and UDP.
Application layer The TCP/IP model merges the session layer and presentation layer functions in the OSI reference model into the application layer.

The applications based on TCP protocol mainly include the following types:

• FTP: File transfer protocol, allowing file transfer on the network.
• TELNET: Virtual terminal protocol, allowing logging in to remote host B from host A.
• HTTP: Hypertext Transfer Protocol, allows the network to transmit hypertext.
• HTTPS: Hypertext Transfer Protocol Secure.
• POP3: Allows users to access and operate mail and mail folders on the luck server.
• IMAP4: Messaging Access Protocol version 4, allows users to access and operate mail and mail folders on the Yuanyun server.
• SMTP: Protocol for sending emails.

Application layer protocol based on UDP protocol:

• SNMP: Simple Network Management Protocol provides a standardized way to manage local and remote network devices and is a distributed Centralized management protocol in a centralized environment.
• DNS: Domain Name System Protocol, which converts the host’s domain name into the corresponding IP address.

IP Protocol

Every host in an IP network (a network using IP protocol) has a unique IP address, and the IP address identifies each host in the network . An IP address is a 32-bit binary number sequence. For example: 192.168.3.4. The network address is obtained by ANDing the IP address with the subnet mask. If the subnet mask is 255.255.255.0, then the network address is: 192.168.3.0

The process of sending data packets

IP is a packet-oriented protocol, that is, data is divided into several small packets and then transmitted separately. Hosts on the IP network can only send data packets directly to other hosts on the local network (that is, hosts with similar IP addresses). The host actually has two real addresses of different natures. When host A sends a packet to another host B on the same network, it will obtain the physical address of the other party through Address Resolution Protocol (ARP), and then give the packet to the other party. The operating mechanism of the ARP protocol is that host A broadcasts an ARP message on the network: "Looking for a host with the address 192.166.3.5." Host B with this IP address will respond and tell A its physical address.

When host A sends a packet to host B on another network:
Host A uses the ARP protocol to find the physical address of the router on the local network and forwards the packet to the router. The router processes the data packet as follows:

  1. If the life cycle of the data packet has expired, the data packet is discarded.

  2. Search the routing table, giving priority to the hosts in the routing table. If a host with the target IP address is found, the data packet is sent to the host.

  3. If the matching host fails, the routing table will continue to be searched for the routing table of the matching subnet. If a matching routing table is found, the packet will be forwarded to the router.

  4. If matching the router on the same subnet fails, continue to search the routing table to match the router on the same network. If a matching router is found, the data packet will be forwarded to the router.

  5. If the above matching fails, the default route is searched. If the default route exists, the data packet is sent according to the default route, otherwise the data packet is discarded.
    The flow chart is as follows:
    Java network programming explained in detail with pictures and text

Domain name

IP is a string of numbers with no meaning. A domain name is a meaningful string of characters or numbers corresponding to an IP. For example: www.google.com
The correspondence between domain name and IP requires a domain name resolution system to convert the domain name into IP. DNS server can solve this problem.

URL (Uniform Resource Locator)

URL (Uniform Resource Location) is an addressing method set up specifically to identify the location of resources on the network. URL generally consists of 3 parts:

应用层协议://主机IP地址或域名/资源所在路径/资源名

For example: http://www.php.cn/ where http refers to Hypertext Transfer Protocol, blog.csdn.net is the domain name of the web server, /article/details/ is the path of the web page, and 54962975 is the corresponding web page file.

TCP protocol and port

When the IP protocol sends data, various problems may occur during the data transmission process. This results in packet loss or incorrect packet order. The TCP protocol enables processes on two hosts to communicate smoothly without worrying about packet loss or out-of-order packets. TCP tracks the order of packets and reassembles them in the correct order if they are messed up. If the packet is lost, TCP will request the source host to resend the packet.

Port

The TCP protocol enables processes on two hosts to communicate smoothly, but there is more than one process on the host. TCP uses ports to distinguish processes. A port is not a physical device, but a logical address used to identify a process. The computer's port range is 0 to 65535, of which ports 0 to 1023 are generally assigned to some services. details as follows:

服务 端口 协议
文件传输服务 21 FTP
远程登录服务 23 TELENET
邮件传输服务 25 SMTP
万维网超文本传输服务 80 HTTP
访问邮件远程邮件服务 110 POP3
互联网消息存取服务 143 IMAP4
安全的超文本传输服务 443 HTTPS
安全的远程登录服务 992 TELNETS
安全互联网消息存取服务 993 IMAPS

Java网络编程入门程序

Java网络程序都建立在TCP/IP协议基础上,在应用层实现。传输层向应用层提供了套接字Socket接口,Socket封装了下层的数据传细节,应用层的程序通过Socket来建立与远程主机的连接,以及数据传输,如下图所示:
Java network programming explained in detail with pictures and text

在Java中,有3种套接字类:java.net.Socketjava.net.ServerSocketjava.net.DatagramSocket 。其中SocketServerSocket 建立在TCP协议上,DatagramSocket 类建立在UDP协议基础上。我们创建EchoServer和EchoClient两个类,我们通过ServerSocketSocket来编写。

创建EchoServer类

在服务端通过一直监听端口,来接收客户程序的连接请求。在服务器程序中,先创建一个ServerSocket对象,在构造方法中指定监听的端口:

ServerSocket server = new ServerSocket(8080);

ServerSocket构造器负责在操作系统中将当前进程注册为服务进程。服务器程序调用ServerSocketaccept()方法来监听端口,等待客户端的连接,如果接收到连接,则accept()方法返回一个Socket对象,这个Socket对象与客户端的Socket对象形成了一条通信线路:

Socket socket = server.accept();

Socket提供了getInputStream()方法和getOutputStream()方法,分别返回输入流InputStream对象和输出流OutputStream对象。程序只需向输出流写入东西,就能向对方发送数据;只需从输入流读取数据,就能接收到数据。如下图:
Java network programming explained in detail with pictures and text
EchoServer 类代码如下:

/**
 * 服务端 服务端类
 *
 */public class EchoServer {


    private ServerSocket serverSocket;    
    public EchoServer(int port) {        
    try {            this.serverSocket = new ServerSocket(port);
            System.out.println("start server success,start port:"+port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }    /**
     * 获取BufferedReader包装类
     * 
     * @param socket
     * @return
     * @throws IOException
     */
    private BufferedReader getReader(Socket socket) throws IOException {        
    return new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }    /**
     * 获取PrintWriter包装类,
     * 
     * @param socket
     * @return
     * @throws IOException
     */
    private PrintWriter getWriter(Socket socket) throws IOException {        
    // 每写一行自动刷新
        return new PrintWriter(socket.getOutputStream(), true);
    }    public void service() {        while (true) {
            Socket socket = null;            try {
                socket = serverSocket.accept();
                System.out.println("new connect,address is:" + socket.getInetAddress() + " port is:" + socket.getPort());
                BufferedReader reader = getReader(socket);
                PrintWriter writer = getWriter(socket);
                String msg = null;                
                while ((msg = reader.readLine()) != null) {                    
                // 读取一行
                    System.out.println("client request  msg: " + msg);
                    writer.println(echo(msg));                    
                    if ("bye".equalsIgnoreCase(msg)) {                        
                    break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{                
            if(socket!=null){                    
            try {                        
            //关闭会话连接
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }    private String echo(String msg) {        return "get request msg is '" + msg+"'";
    }    public static void main(String[] args) {        new EchoServer(8080).service();
    }
}

EchoServer类的最主要的方法就是service()方法,它不断登录客户的连接请求。当serverSocket.accept()返回一个Socket对象时,表示与一个客户端建立了连接。

创建EchoClient

在EchoClient程序中,为了与EchoClient通信,需要先创建一个Socket对象:

String host="localhost";int port = 8080;new Socket(host, port);

host表示Server进程所在服务器的地址,port表示Server进程监听的端口。当参数host为’localhost’时,表示服务端和客户端在同一台机器上。下面是EchoClient类的源码:

public class EchoClient {
    private Socket socket;    
    public EchoClient(String host,int port){        
    try {            this.socket = new Socket(host, port);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }    /**
     * 获取BufferedReader包装类
     * 
     * @param socket
     * @return
     * @throws IOException
     */
    private BufferedReader getReader(Socket socket) throws IOException {        
    return new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }    /**
     * 获取PrintWriter包装类,
     * 
     * @param socket
     * @return
     * @throws IOException
     */
    private PrintWriter getWriter(Socket socket) throws IOException {        
    // 每写一行自动刷新
        return new PrintWriter(socket.getOutputStream(), true);
    }    public void talk(){        try {
            BufferedReader reader = getReader(socket);
            PrintWriter writer = getWriter(socket);
            BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
            String msg = null;            
            while((msg=localReader.readLine())!=null){
                writer.println(msg);
                System.out.println("server response msg:"+reader.readLine());                
                if("bye".equalsIgnoreCase(msg)){                    
                break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{            
        if(socket!=null){                
        try {
                    socket.close();
                    System.out.println("has been disconnected");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }    public static void main(String[] args) {        
    new EchoClient("localhost", 8080).talk();
    }
}

在EchoClient类中最重要的是talk()方法,该方法不断读取用户从控制台输入的字符串,然后将它发送到EchoServer,在把EchoServer返回的数据打印在控制台。如果输入’bye’字符串,就会结束与EchoServer的通信,调用socket.close()方法端口连接。
具体运行如下图,一个是服务端一个是客户端的控制台:
Java network programming explained in detail with pictures and text

总结

简单介绍了一下网络的理论知识和TCP/IP协议。并使用Java实现了一个网络通信程序。

 以上就是Java网络编程由浅入深一图文详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn