Java: Network Programming

1 Overview

  • Java is a language on the Internet. It provides support for network applications from the language level, and programmers can easily develop common network applications.
  • The network class library provided by Java can realize painless network connection. The underlying details of the network are hidden in Java's native installation system and controlled by the JVM. And Java implements a cross-platform network library, and programmers are faced with a unified network programming environment.

2. Network foundation

  • Computer network:
    Connect computers distributed in different geographical areas with specialized external equipment using communication lines to form a large-scale, powerful network system, so that numerous computers can easily transmit information to each other, share hardware, software, and data Information and other resources.
  • The purpose of network programming:
    directly or indirectly realize data exchange and communication with other computers through network protocols.
  • There are two main problems in network programming:
    how to accurately locate one or more hosts on the network; and locate specific applications on the host.
    How to perform data transmission reliably and efficiently after finding the host.

3. Network communication

  • Network communication is based on the addresses of both parties in communication, which are determined by IP and port.
  • Network communication needs to follow the network communication protocol.
    (1) OSI reference model: The model is too idealistic and cannot be widely promoted on the Internet.
    (2) TCP/IP reference model (or TCP/IP protocol): the current international standard.

3.1 IP address

The ip address is the unique identification of a computer on the Internet.

Local loopback address (hostAddress): 127.0.0.1

Host Name (hostName): localhost

IP address classification method 1: IPV4 and IPV6

  • IPV4: 4 bytes, 4 0-255. About 4.2 billion, 3 billion are in North America, 400 million in Asia. It was exhausted in early 2011. Expressed in dotted decimal notation, such as 192.168.0.1
  • IPV6: 128 bits (16 bytes), written as 8 unsigned integers, each integer is represented by four hexadecimal digits, and the numbers are separated by colons (:), such as: 3ffe:3201:1401:1280 :c8ff:fe4d:db39:1984

IP address classification method 2: public network address (used by the World Wide Web) and private address (used by the local area network).

  • The address at the beginning is the private address, the range is 192.168.0.0–192.168.255.255, which is specially used for the internal use of the organization.
    Features: not easy to remember

3.2 port

The port number identifies the process (program) running on the computer. Different processes have different port numbers, which are defined as a 16-bit integer 0~65535.

Port classification:

  • Recognized port: 0~1023. Occupied by predefined service communications (for example: HTTP occupies port 80, FTP occupies port 21, Telnet occupies port 23)
  • Registered port: 1024~49151. Assigned to a user process or application. (For example: Tomcat occupies port 8080, MySQL occupies port 3306, Oracle occupies port 1521, etc.).
  • Dynamic/private port: 49152~65535.

4. OSI seven layers

The seven layers of OSI are application layer, presentation layer, session layer, transport layer, data link layer, physical layer, and network layer.

  • Application layer: The application layer is the service window provided by the network to users. It is mainly used to support the needs of users. The needs of people are different, and the application layer technology
    provides a variety of application services: email (MHS), file transfer ( FTAM), Virtual Terminal (VT), Electronic Data Interchange (EDI), etc.
    Main protocols: FTP(21), SMTP(25), DNS.HTTP(80)

  • Presentation layer: Provide a common language for communication to facilitate interaction, because different computer system structures use different data representations, for example: IBM hosts use EBCDIC encoding, and most PCs use ASCII encoding.
    Other functions such as Data encryption, data compression

  • Session layer: The services provided can enable applications to establish and maintain sessions, and can synchronize sessions.Transport
    layer: When computers communicate data through the network for two days, it is an end-to-end level and has a buffering
    effect.Protocol: TCP/UDP

  • Physical layer: Provides a path for data segment equipment to transmit data. The data path can be a physical medium or a connection of multiple physical media.

  • Data link layer: can be understood as a data channel,
    MAC address represents uniqueness

  • Network layer: IP, data transfer in the form of IP messages

5. Network protocol

5.1 TCP/IP (Transmission Control Protocol)

  • TCP/IP is named after its two main protocols: Transmission Control Protocol (TCP) and Internet Interconnection Protocol (IP). In fact, it is a set of protocols, including multiple protocols with different functions and related to each other.
  • The IP (Internet Protocol) protocol is the main protocol of the network layer and supports data communication between networks.
  • From a more practical perspective, the TCP/IP protocol model forms an efficient four-layer system structure, namely, the physical link layer, the IP layer, the transport layer, and the application layer.
  • Retransmission is possible, no packet loss, if lost, it will record and resend, but it will not be repeated, reliable
  • Ordered, the order is not wrong, such as sending you 123, 2 is lost, and retransmitted, then you may receive 132, but what you see must be 123
  • For the link, if the connection fails, the data will not be sent
  • The three-way handshake can ensure the security of the data and ensure the interaction
  • It is equivalent to making a call, if you can't get through, the data can't be communicated

5.1.1 Socket

  • The use of sockets to develop network applications has long been widely adopted, so that it has become a de facto standard.
  • Only the uniquely identified IP address and port number on the network can be combined to form a uniquely identifiable identifier socket.
  • Both ends of the communication must have a Socket, which is the endpoint of communication between the two machines.
    Network communication is actually the communication between Sockets.
  • Socket allows the program to treat the network connection as a stream, and data is transmitted between the two Sockets via IO.
  • Generally, the application that initiates communication is the client, and the one waiting for the communication request is the server.

Socket classification:

  • Stream socket: Use TCP to provide reliable byte stream services
  • Datagram socket: Use UDP to provide "best effort" datagram service

5.1.2 Common methods

Commonly used constructors of the Socket class:

  • public Socket(InetAddress address,int port) creates a stream socket and connects it to the specified port number of the specified IP address.
  • public Socket(String host,int port) creates a stream socket and connects it to the specified port number on the specified host.

Common methods of the Socket class:

  • public InputStream getInputStream() returns the input stream of this socket. Can be used to receive network messages
  • public OutputStream getOutputStream() returns the output stream of this socket. Can be used to send network messages
  • public InetAddress getInetAddress() The remote IP address that this socket is connected to; if the socket is not connected, it returns null.
  • public InetAddress getLocalAddress() Get the local address bound to the socket. That is, the IP address of the local end
  • public int getPort() The remote port number this socket is connected to; if the socket is not connected yet, 0 is returned.
  • public int getLocalPort() Returns the local port to which this socket is bound. If the socket has not been bound, -1 is returned. That is, the port number of the local end.
  • public void close()Close this socket. After the socket is closed, it cannot be used in future network connections (that is, it cannot be reconnected or re-bound). Need to create a new socket object. Closing this socket will also close the InputStream and OutputStream of the socket.
  • public void shutdownInput() If you call shutdownInput() on the socket and then read content from the socket input stream, the stream will return EOF (End of File). That is, no data can be received in the input stream from this socket.
  • public void shutdownOutput() disables the output stream of this socket. For TCP sockets, any previously written data will be sent, followed by TCP's normal connection termination sequence. If you call shutdownOutput() on the socket and then write to the socket output stream, the stream will throw an IOException. That is, no data can be sent through the output stream of this socket.

5.1.3 Server

*The working process of the server program includes the following four basic steps:
(1) Call ServerSocket(int port): Create a server-side socket and bind it to the specified port. Used to monitor client requests.
(2) Call accept(): listen to the connection request, if the client requests a connection, then accept the connection and return the communication socket object.
(3) Call getOutputStream() and getInputStream() of the Socket class object: Obtain the output stream and input stream, and start sending and receiving network data.
(4) Close the ServerSocket and Socket objects: the client access ends and the communication socket is closed.

The ServerSocket object is responsible for waiting for the client's request to establish a socket connection, similar to a salesperson in a window of a post office. In other words, the server must establish in advance a ServerSocket object waiting for the client to request to establish a socket connection.

The so-called "receiving" the client's socket request is that the accept() method will return a Socket object

5.1.4 Client

The working process of the client Socket includes the following four basic steps:
(1) Create Socket: Construct a Socket class object according to the IP address or port number of the specified server. If the server responds, a communication line from the client to the server is established. If the connection fails, an exception will occur.
(2) Open the input/output stream connected to the Socket: Use the getInputStream() method to obtain the input stream, use the getOutputStream() method to obtain the output stream, and perform data transmission
(3) Read/write the Socket according to a certain protocol: pass The input stream reads the information that the server puts into the line (but cannot read the information that the server puts into the line), and writes the information to the thread through the output stream.
(4) Close Socket: disconnect the connection from the client to the server and release the line

The client program can use the Socket class to create an object, and it will automatically initiate a connection to the server when it is created.

The constructor of Socket is:

  • Socket(String host,int port)throws UnknownHostException, IOException: initiate a TCP connection to the server (domain name is host. Port number is port), if successful, create a Socket object, otherwise throw an exception.

  • Socket (InetAddress address, int port) throws IOException: Initiate a connection based on the IP address and port number port represented by the InetAddress object.

The process of establishing a socketAtClient object by the client is to send a socket connection request to the server

5.2 UDP

5.2.1 Overview
  • Fast speed and poor reliability
  • No connection, it is equivalent to sending a short message, whether you can receive it or not, it will be sent to you anyway. The
    classes DatagramSocket and DatagramPacket implement network programs based on the UDP protocol.
  • UDP datagrams are sent and received through the datagram socket DatagramSocket. The system does not guarantee that UDP datagrams can be safely delivered to the destination, nor can it be determined when they will arrive.
  • The DatagramPacket object encapsulates the UDP datagram. The datagram contains the IP address and port number of the sender and the IP address and port number of the receiver.
  • Each datagram in the UDP protocol gives complete address information, so there is no need to establish a connection between the sender and the receiver. It's like sending a parcel.
5.2.2 Common methods

Common methods of the DatagramSocket class:

  • public DatagramSocket(int port) creates a datagram socket and binds it to the specified port on the local host. The socket will be bound to a wildcard address, and the IP address will be chosen by the kernel.
  • public DatagramSocket (int port, InetAddress laddr) creates a datagram socket and binds it to the specified local address. The local port must be between 0 and 65535 (including both). If the IP address is 0.0.0.0, the socket will be bound to a wildcard address, and the IP address is chosen by the kernel.
  • public void close()Close this datagram socket.
  • public void send(DatagramPacket p) sends a datagram packet from this socket. The information contained in DatagramPacket indicates: the data to be sent, its length, the IP address of the remote host and the port number of the remote host.
  • public void receive(DatagramPacket p) Receive datagram packet from this socket. When this method returns, the buffer of DatagramPacket is filled with the received data. The datagram packet also contains the IP address of the sender and the port number on the sender's machine. This method blocks until the datagram is received. The length field of the datagram packet object contains the length of the received information. If the information is longer than the length of the packet, the information will be truncated.
  • public InetAddress getLocalAddress() Get the local address bound to the socket.
  • public int getLocalPort() returns the port number on the local host to which this socket is bound.
  • public InetAddress getInetAddress() returns the address of this socket connection. If the socket is not connected, null is returned.
  • public int getPort() returns the port of this socket. If the socket is not connected, -1 is returned.

Common methods of DatagramPacket class

  • public DatagramPacket(byte[] buf,int length) constructs DatagramPacket to receive
    data packets of length length. The length parameter must be less than or equal to buf.length.
  • public DatagramPacket(byte[] buf,int length,InetAddress address,int port) constructs a datagram packet, which is used to send a packet of length length to the specified port number on the specified host. The length parameter must be less than or equal to buf.length.
  • public InetAddress getAddress() returns the IP address of a machine to which this datagram will be sent
    or received.
  • public int getPort() returns the port number of a remote host, this datagram will be sent to or received from the host.
  • public byte[] getData() returns the data buffer. The received or to-be-sent data starts
    at the offset offset in the buffer and continues for length length.
  • public int getLength() returns the length of the data to be sent or received.
5.2.3 Server

1. DatagramSocket and DatagramPacket
2. Establish the sender and receiver
3. Create a data packet
4. Call the sending and receiving methods of the
Socket 5. Close the Socket

The sender and receiver are two independent running programs

public static void main(String[] args) throws Exception {
    
    
		// 打开UDP对象
		DatagramSocket ds = new DatagramSocket(10000);
		// 声明字节数组,用来存放收到的数据
		byte[] buf = new byte[1024];
		// 包接收器,把接收的数据保存到数组中
		DatagramPacket dp = new DatagramPacket(buf, buf.length);
		// 阻塞式接收
		while (true) {
    
    
			// 监听接收
			ds.receive(dp);
			// 字节数字输入流
			ByteArrayInputStream bais = new ByteArrayInputStream(buf);
			// 转换为数据流
			DataInputStream dis = new DataInputStream(bais);
			// 读取数据
			String msg = dis.readUTF();
			// 如果是exit 则结束服务端
			if (msg.equalsIgnoreCase("exit")) {
    
    
				break;
			}
			System.out.println(msg);
		}
	}
5.2.4 Client
	// 一次发送
	public static void test01() throws Exception {
    
    
		// 发送的数据
		String str = "你好";
		// 字节数字输出流
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		// 写出数据到baos
		dos.writeUTF(str);
		// 把baos转换为字节数组
		byte[] buf = baos.toByteArray();
		// 发送数据,大小限制是64K,绑定地址
		DatagramPacket dp = new DatagramPacket(buf, buf.length,
				new InetSocketAddress("127.0.0.1", 10000));
		// 发送,需要通过电脑中一个端口发送出去
		DatagramSocket ds = new DatagramSocket(9999);
		// DatagramPacket 数据包
		// DatagramSocket 通信
		ds.send(dp);
		ds.close();
	}

	// 持续发送
	public static void test02() throws Exception {
    
    
		// 发送的数据
		String str = null;
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入需要传递的信息 : ");
		// 获取输入的数据
		str = sc.nextLine();
		while (str != null ) {
    
    
			// 字节数字输出流
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(baos);
			// 写出数据到baos
			dos.writeUTF(str);
			// 把baos转换为字节数组
			byte[] buf = baos.toByteArray();

			// 发送数据,大小限制是64K,绑定地址
			DatagramPacket dp = new DatagramPacket(buf, buf.length,
					new InetSocketAddress("127.0.0.1", 10000));

			// 发送,需要通过电脑中一个端口发送出去
			DatagramSocket ds = new DatagramSocket(9999);
			// DatagramPacket 数据包
			// DatagramSocket 通信
			ds.send(dp);
			ds.close();
			// 如果是exit  则退出客户端
			if (str.equalsIgnoreCase("exit")) {
    
    
				break;
			}
			System.out.println("请输入需要传递的信息 : ");
			// 获取输入的数据
			str = sc.nextLine();
		}
	}

Guess you like

Origin blog.csdn.net/qq_41504815/article/details/113530546