Network Programming (30) java in

An overview of network programming

Network communication protocol

Here Insert Picture Description

1, network programming purposes:

      Implemented with other computers either directly or indirectly through a network protocol for data exchange, communication

2, Network Programming There are two main issues:

      ①, how accurately positioned on the specific applications on the network one or more hosts, host by

      ②, the host how to find reliable and efficient data transmission

3, a communication elements: IP and port number

      ①, IP: computer (communication entity) on the Internet unique identifier

      ②, use InetAddress class represents the IP in Java

      ③, IP classification: IPV4 and IPV6; WAN LAN

Classification IP addresses

  • IP address classification 1 : IPV4 and IPV6

            The IPV4 : 4 bytes, four 0-255. About 4.2 billion, 3 billion in North America, Asia 400 million. In early 2011 it has
been exhausted. In dotted decimal notation, such as 192.168.0.1

            IPV6 : 128 bits (16 bytes) is written as 8 unsigned integers, each integer expressed by four hexadecimal digits,
with a colon (:) separation between the numbers, such as: 3ffe: 3201: 1401: 1280 : c8ff: fe4d: db39: 1984

  • IP address classification 2 : public address (World Wide Web) and a private address (local area network use) . 192.168.
    The beginning of the site address is private, 192.168.0.0-192.168.255.255 range that is specifically for tissue machine
    uses an internal mechanism

Port Category :

  • Recognized port : 0 to 1023. Communication service to be occupied by a pre-defined (e.g., HTTP port occupies 80)

  • Registration port : 1024 to 49151. Assigned to the user process or application. (Eg: Tomcat occupied port 8080, mysql occupy the port 3306, oracle 1521 occupation, etc.)

  • Dynamic / private ports : 49152 to 65535.

Port number : running processes on the computer. Requirements: Different processes have different port numbers

IP address port number combinations come with a network socket: Socket

4, TCP and UDP

TCP protocol:

      Before using the TCP protocol, must first establish a TCP connection, the data transmission path is formed

      Before transmission, a "three-way handshake" mode, point to point communication, reliable

      TCP protocol to communicate with two application processes: client, server

      In connection can transfer large amounts of data

      Transfer is completed, the need to release an established connection, low efficiency (call)

UDP protocol:

      Data, source and destination encapsulation into packets, without establishing a connection

      The size of each datagram within the 64K limit

      Regardless of whether the other party is ready to send, the recipient does not receive an acknowledgment, it is not reliable

      Can broadcast transmission (send text messages, telegram)

      At the end of transmitting data without releasing resources, small overhead, fast

TCP three-way handshake

Here Insert Picture Description

Four waving

Here Insert Picture Description

TCP code is implemented as follows:

//客户端
@Test
public void client() {
    //1,创建Socket对象,指明服务器端的ip和端口号
    Socket socket = null;
    //2,获取一个输出流,用于输出数据
    OutputStream outputStream = null;
    try {
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        socket = new Socket(inetAddress, 9999);
        outputStream = socket.getOutputStream();
        //3,写出数据
        outputStream.write("你好啊,很高兴认识you!".getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4,关闭资源
        try {
            if (socket != null) {
                socket.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//服务端
@Test
public void server() {
    //1,创建服务器端的ServerSocket,指明自己的端口号
    ServerSocket serverSocket = null;
    //2,调用accept()表示接收来自于客户端的socket
    Socket socket = null;
    //3,获取输入流
    InputStream inputStream = null;
    try {
        serverSocket = new ServerSocket(9999);
        socket = serverSocket.accept();
        inputStream = socket.getInputStream();

        //4,读取输入流中的数据
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[5];
        int len;
        while ((len = inputStream.read(buffer)) != -1){
            byteArrayOutputStream.write(buffer, 0, len);
        }
        System.out.println(byteArrayOutputStream.toString());
        System.out.println("收到了来自"+socket.getInetAddress().getHostAddress());
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        //5,资源关闭
        try {
            if (serverSocket != null){
                serverSocket.close();;
            }
            if (socket != null){
                socket.close();;
            }
            if (inputStream != null){
                inputStream.close();;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

UDP code is implemented as follows:

//发送端
public void sender() {
    DatagramSocket datagramSocket = null;
    try {
        datagramSocket = new DatagramSocket();
        byte[] data = "我是以UDP方式发送".getBytes();
        DatagramPacket datagramPacket = new DatagramPacket(data, 0, data.length, InetAddress.getByName("127.0.0.1"), 9999);
        datagramSocket.send(datagramPacket);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (datagramSocket != null) {
            datagramSocket.close();
        }
    }
}

@Test
//接收端
public void server() {
    DatagramSocket datagramSocket = null;
    try {
        datagramSocket = new DatagramSocket(9999);
        byte[] bytes = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
        datagramSocket.receive(datagramPacket);
        String str = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
        System.out.println(str + "------" + datagramPacket.getAddress());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (datagramSocket != null) {
            datagramSocket.close();
        }
    }
}

5, URL category

The URL of (Uniform Resource Locator) : Uniform Resource Locator, which indicates the address of a resource on the Internet

The basic structure of the URL consists of 5 parts :

        <Transfer Protocol>: // <hostname>: <port number> / <filename> # fragment name parameter list?

URL url = new URL("http://localhost:8080/examples/Test.txt?userName=Tom");
System.out.println("获取该URL的协议名:"+url.getProtocol());//http
System.out.println("获取该URL的主机名 :"+url.getHost());//localhost
System.out.println("获取该URL的端口号 :"+url.getPort());//8080
System.out.println("获取该URL的文件路径 :"+url.getPath());// /examples/Test.txt
System.out.println("获取该URL的文件名 :"+url.getFile());// /examples/Test.txt?userName=Tom
System.out.println("获取该URL的查询名 :"+url.getQuery());//userName=Tom

Next chapter (31) reflection

Published 67 original articles · won praise 19 · views 9870

Guess you like

Origin blog.csdn.net/qq_41530004/article/details/104053064