Java learning record Day20 (network programming)

Day 20

May 26, 2019.
This is what I learned Java twenty days.
On this day, I learned the following knowledge.

computer network

Computer network, the computer is located in different geographic regions with specialized external devices interconnected by communications lines to be larger scale a strong function of the network system, so that a large number of computers can easily transmit information to each other, sharing of hardware, software, data and other information resources.
Which has the following key concepts:

  • The main function of computer networks :
    - resource sharing
    - information transmission and focus on
    - load balancing and distributed processing
    - an integrated information service (www / Integrated Services Digital Network ISDN)

  • Network communication protocol : a computer network for communication must be some conventions, i.e., communication protocol; develop standards for speed, transmitting a code, the code structure, the transmission control step, an error control.

  • Network communication interface : To enable a dialogue between two nodes, you must establish communications tools (ie the interface) between them, so that between each other, to exchange information. Interface consists of two parts:
    - a hardware device: to achieve information transmission between nodes
    - software means: a predetermined communication protocol agreed between the two sides

  • Hierarchical thinking : Due to the link between nodes is very complex, in the development agreement, the complex components broken down into a few simple ingredients, and then composite them together. The most common way is complex inter-level way, and can communicate with the layer, the layer can be called the next layer, and the relationship with the next layer does not occur. Each layer independently of each other, conducive to the development and expansion of the system.

  • Reference Model : OSI reference model and is divided into TCP / IP reference model, as shown in FIG principle:Here Insert Picture Description

  • IP protocol : Each person's computer has a unique IP address, communicate with each other when this would not pass the wrong information. The IP address is divided into sections with a point, and a computer-internal IP address is represented by four bytes, one byte representative of a piece, the maximum number of each byte represents only reaches 255, the following diagram below:
    Here Insert Picture Description

  • Communication : TCP and UDP at the same level, are based on the IP layer. Due to different IP addresses between two computers, two computers can therefore be distinguished, we can call each other up. There are two general call call ways: The first is TCP, the second is UDP.
    - TCP (Transmission Control Protocol Transmission Control Protocol): TCP like to call, you need to open up the other phone, waiting for the other party will continue to speak to each other after responds, that is, be sure to confirm the information will later be sent to the information sent out . TCP upload everything is reliable, as long as the established connection on both machines, data transmitted on the machine will be able to spread to other machines.
    - UDP (User Datagram Protocol User Datagram Protocol): UDP is like a telegram, sent opinions on the bin, the other side has received it do not care, so UDP is not reliable.
    Although reliable TCP transport data, but slower than the transfer, UDP data transfer unreliable, but faster transmission.

  • The Socket : two computers installed on a socket, then both ends of a cable into a socket on the two computers, two computers is established so that a good connection. The socket is Socket.

  • Server (server-side) and Client (client) : Because each other can communicate with each other, I say you are my Server but logically speaking, I should put things starting to come to you, then come to you processing, forwarding. So you called Server. But from a technical sense, points will only TCP Server and Client. For UDP is, strictly speaking, no such thing as Server and Client. The Server TCP socket called ServerSocket, Client socket called Socket. FIG principle is as follows:
    Here Insert Picture Description

  • Port number : two computers connected to each other, you must first get to know their IP address, but only the IP address is not enough, it must be connected to the port number, which is to be connected to which application. The port number is used to distinguish between different applications on a machine table . Inside the computer port number is 2 bytes. Up to 65,536 port numbers on a machine. An application can occupy multiple port numbers. If a port number is occupied by the application, other applications will no longer be able to use this port number. Remember that we are prepared to take up the program, then the port number occupy more than 1024 port numbers, port numbers below 1024 not to occupy, because the system is subject to expropriation. Port number itself is divided into TCP and UDP port, TCP port 8888 and UDP port 8888 are two completely different ports. TCP and UDP port has 65,536.

network programming

Network programming in Java communication scheme is divided into two:

  • UDP programmed
    core classes of DatagramSocket and DatagramPacket, schematics follows:
    Here Insert Picture Description
    Code Examples below:
    1. The client

    public class Client {
    public static void main(String[] args) throws IOException {
        //1 指定端口 DatagramSocket
        DatagramSocket socket = new DatagramSocket();
    
        //2 指定一个IP
        InetAddress addr = InetAddress.getByName("127.0.0.1");
        int port = 5051;
    
        //3 准备一个容器
        byte[] sendBuf = new byte[1024];
        while (true){
            Scanner scanner = new Scanner(System.in);
            System.out.println("发送什么?");
            String s = scanner.nextLine();
            //4 加入要放的数据
            sendBuf = s.getBytes();
    
            //5 数据打包
            DatagramPacket packet = new DatagramPacket(sendBuf,sendBuf.length,addr,port);
    
            //6 发送包
            socket.send(packet);
    
            if (s.equals("exit")){
                break;
            }
        }
    
        //7.释放资源
        socket.close();
    }
    }
    

    2. server

public class Server {
    public static void main(String[] args) throws IOException {
        //1 指定端口 DatagramSocket
        DatagramSocket socket = new DatagramSocket(5051);

        //2 准备一个容器,封包 DatagramPacket
        byte[] receiveBuf = new byte[1024];

        //3 等待接收包 receive()
        DatagramPacket packet = new DatagramPacket(receiveBuf,receiveBuf.length);
        System.out.println("等待包......");
        while (true){
            //4 接收包
            socket.receive(packet);

            //5.解析包
            String receStr = new String(packet.getData(),0,packet.getLength());
            System.out.println("我收到的数据:" + receStr);
            if (receStr.equals("exit")){
                break;
            }
        }

        //6 释放资源
        socket.close();
    }
}
  • TCP programmed
    core classes of ServerSocket and Socket, schematics as follows:
    Here Insert Picture Description
    Code Examples below:
    1. The client

    public class Server{
    public static void main(String args[]) throws Exception{
        Socket s = new Socket("127.0.0.1",6666);
        /*Client申请连接到Server端上*/
        /*连接上服务器端以后,就可以向服务器端输出信息和接收从服务器端返回的信息
        输出信息和接收返回信息都要使用流式的输入输出原理进行信息的处理*/
        /*这里是使用输出流OutputStream向服务器端输出信息*/
        OutputStream os = s.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        Thread.sleep(30000);/*客户端睡眠30秒后再向服务器端发送信息*/
        dos.writeUTF("Hello Server!");
    }
    }
    

    2. server

public class Server{
    public static void main(String args[]) throws Exception{
        ServerSocket ss = new ServerSocket(6666);
        /*创建一个ServerSocket对象时往往会给它指定一个端口号
                指定端口号的意思是这个new出来的ServerSocket对象要使用的
                是哪一个端口号,通过哪一个端口号来监听客户端的连接
                因此指定一个端口号的意义就是为了告诉计算机ServerSocket对象
                在哪个地方监听客户端的连接*/
        /*服务器端接收客户端连接的请求是不间断地接收的,所以服务器端的
                编程一般都是死循环,永不休止地运行着。*/
        while(true){
            Socket s = ss.accept();
            /*在服务器端调用accept()方法接受客户端的连接对象,accept()方法是
                            一个阻塞式方法,一直在傻傻地等待着是否有客户端申请连接上来
                            然后服务器端的Socket插座就和客户端的Socket插座建立了连接了*/
            /*客户端能否连接上服务器端,取决于服务器端是否接受客户端的连接请求
                            如果接受了客户端的连接请求,那么在服务器端就安装上一个Socket插座
                            通过这个插座与连接上的客户端就可以建立连接,互相通信了*/
            System.out.println("A Client Connected!");
            /*使用InputStream流接收从客户端发送过来的信息,使用DataInputStream数据流处理接收到的信息*/
            DataInputStream dis = new DataInputStream(s.getInputStream());
            /*使用readUTF(方法将接收到的信息全部读取出来,存储到变量str里面
                            readUTF()方法也是一个阻塞式方法,会傻傻地等待客户端发送信息过来,然后将接收到的信息读取出来
                            如果客户端不写东西过来,它就一直在服务器端傻傻地等待着,直到客户端写东西过来为止
                            堵塞式的方法效率往往是不高的,比如说一个客户端连接上来了,但是它迟迟不发送信息,
                            那么服务器端的程序就阻塞住了,这样另外一个客户端就连接不上来了,因为另外一个客户端要想连接
                            上服务器端,就必须得在服务器端调用accept()方法,可accept()方法必须得在下一次循环时才能够被
                            调用,现在服务器端的程序运行到调用readUTF()这个方法时就阻塞住了,它要等待着已经连接上来的
                            那个客户端发送信息过来后将信息读取出来,如果客户端一直不发信息到服务器端,那么readUTF()方法
                            就一直无法读取到信息,那么服务器端的程序会阻塞在这里,无法进行下次循环,这样其他的客户端就
                            无法连接到服务器端了*/
            String str = dis.readUTF();
            System.out.println(str);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_41151659/article/details/90611755