Table of contents
Overview of Network Programming
The purpose of network programming
Overview of Network Communication Elements
Communication element 1: ip address and port number
Communication Element 2: Network Protocol
Common constructors of the Socket class
Common methods of Socket class
Common methods of the DatagramSocket class
Common methods of DatagramPacket packets
Overview of Network Programming
Java is a language on the Internet. It provides support for network applications at 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 networking are hidden in Java's native installation system and controlled by JVM. Moreover, Java implements a cross-platform network library, and programmers are faced with a unified network programming environment.
network foundation
Computer network:
interconnect computers distributed in different geographic regions and specialized external devices with communication lines to form a large-scale and powerful network system, so that many computers can easily transmit information to each other and share hardware, software, and data information and other resources.
The purpose of network programming
Data exchange and communication with other computers directly or indirectly through network protocols.
There are two main problems in network programming:
how to accurately locate one or more hosts on the network; how to locate specific applications on the host;
how to reliably and efficiently transmit data after finding the host
Overview of Network Communication Elements
Address of both parties
- IP
- The port number
Certain rules (ie: network communication protocol. There are two sets of reference models)
- OSI reference model: the model is too idealized and has not been widely promoted on the Internet
- TCP/IP Reference Model (or TCP/IP Protocol): The De facto International Standard
network communication protocol
Communication element 1: ip address and port number
IP address: InetAddress
Uniquely identifies a computer (communication entity) 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 in North America, 400 million in Asia. Early 2011
was exhausted. Expressed in dotted decimal, 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
colons (:) are used between numbers Separate, such as: 3ffe:3201:1401:1280:c8ff:fe4d:db39:1984
IP address classification method 2: public network address (used by World Wide Web) and private address (used by LAN). The beginning of 192.168. is the private address, the range is 192.168.0.0--192.168.255.255, which is specially used for internal use of the organization
. Features: not easy to remember
The port number
The port number identifies the process (program) that is running on the computer
Different processes have different port numbers,
which are specified as a 16-bit integer 0~65535.
Port classification:
- Well-known ports: 0~1023. Occupied by predefined service communication (for example: HTTP occupies port 80, FTP occupies port 21, Telnet occupies port 23)
- Register 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 ports: 49152~65535.
The combination of port number and IP address results in a network socket: Socket.
InetAddress class
There are two ways to indicate the address of the host on the Internet:
domain name (hostName): www.atguigu.com
IP address (hostAddress): 202.108.35.210
- InetAddress class mainly represents IP address, two subclasses: Inet4Address, Inet6Address.
- The InetAddress class object contains the domain name and IP address of an Internet host address: www.atguigu.com and 202.108.35.210.
The domain name is easy to remember. When you enter the domain name of a host when connecting to the network, the domain name server (DNS) is responsible for converting the domain name into an IP address, so that a connection can be established with the host. -------DNS
The InetAddress class does not provide a public constructor, but provides the following static methods to obtain
InetAddress instances
public static InetAddress getLocalHost()
public static InetAddress getByName(String host)
InetAddress provides the following commonly used methods
public String getHostAddress():返回 IP 地址字符串(以文本表现形式)。
public String getHostName():获取此 IP 地址的主机名
public boolean isReachable(int timeout):测试是否可以达到该地址
Communication Element 2: Network Protocol
Overview of Network Protocols
Network communication protocol:
There must be some agreement to realize communication in the computer network, that is, communication protocol, which sets standards for speed, transmission code, code structure, transmission control steps, error control , etc.
Problem: The network protocol is too complicated.
Computer network communication involves a lot of content, such as specifying source and destination addresses, encryption and decryption, compression and decompression, error control, flow control, and routing control. How to implement such a complex network protocol?
The idea of communication protocol layering:
When formulating a protocol, decompose complex components into some simple components, and then compound them. The most commonly used composite method is the hierarchical method, that is, the same layer can communicate, the upper layer can call the lower layer, and has no relationship with the next layer. Each layer does not affect each other, which is conducive to the development and expansion of the system.
TCP/IP protocol suite
There are two very important protocols in the transport layer protocol:
Transmission Control Protocol TCP (Transmission Control Protocol)
User Datagram Protocol UDP (User Datagram Protocol).
TCP/IP, named after its two main protocols: Transmission Control Protocol (TCP) and Internet Protocol (IP), is actually a set of protocols including multiple interrelated protocols with different functions.
IP (Internet Protocol) protocol is the main protocol of the network layer, supporting the data communication between the Internet.
The TCP/IP protocol model forms an efficient four-layer architecture from a more practical point of view, namely the physical link layer, IP layer, transport layer and application layer.
TCP and UDP
TCP protocol:
- Before using the TCP protocol, a TCP connection must be established to form a transmission data channel
- Before transmission, the "three-way handshake" method, point-to-point communication, is reliable
- Two application processes that communicate with the TCP protocol: client and server.
- A large amount of data can be transferred in the connection
- After the transmission is completed, the established connection needs to be released, which is inefficient
UDP protocol:
- Encapsulate data, source, and destination into packets without establishing a connection
- The size of each datagram is limited to 64K
- Regardless of whether the sender is ready or not, the receiver does not confirm receipt, so it is unreliable
- Can broadcast
- There is no need to release resources at the end of sending data, with low overhead and fast speed
Confirm that the sender can send the message the first time
The second time confirms that the receiver can accept the message and send the message
The third time to confirm that the receiver can accept the message
Socket
The use of sockets (Socket) to develop network applications has long been widely used, so that it has become a de facto standard.
The combination of the uniquely identified IP address and port number on the network constitutes a uniquely identifiable identifier socket.
There must be Socket at both ends of the communication, which is the endpoint of communication between two machines.
Network communication is actually communication between Sockets. Socket allows programs to treat network connections as a stream, and data is transmitted between two Sockets through IO. Generally, the application that initiates the communication is the client, and the application that waits for the communication request is the server.
Socket classification:
- Stream socket (stream socket): use TCP to provide reliable byte stream services
- Datagram socket: Provides "best effort" datagram service using UDP
Common constructors of the Socket class
public Socket(InetAddress address,int port)
Creates a stream socket and connects it to the specified port number at 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 Socket class
public InputStream getInputStream()
Returns the input stream for this socket. Can be used to receive network messages
public OutputStream getOutputStream()
Returns the output stream for this socket. Can be used to send network messages:
public InetAddress getInetAddress()
the remote IP address to which this socket is connected, or null if the socket is unconnected
public InetAddress getLocalAddress()
Get the local address to which the socket is bound. That is, the local IP address
public int getPort()
the remote port number this socket is connected to, or 0 if the socket is not already connected
public int getLocalPort()
Returns the local port this socket is bound to. Returns -1 if the socket has not been bound. That is, the port number of the local end
public void close()
Close this socket. Once a socket is closed, it cannot be used for further network connections (i.e. it cannot be reconnected or rebinded). A new socket object needs to be created. Closing this socket will also close the socket's InputStream and OutputStream
public void shutdownInput()
If something is read from a socket input stream after shutdownInput() has been called on the socket, the stream will return EOF (End of File). i.e. cannot receive any data in the input stream from this socket
public void shutdownOutput()
Disables the output stream for this socket. For TCP sockets, any previously written data will be sent,
followed by TCP's normal connection termination sequence. The socket output stream will throw an IOException if written to after shutdownOutput() has been called on the socket. i.e. no data can be sent over this socket's output stream
TCP network programming
The socket-based programming of the Java language is divided into server-side programming and client-side programming, and its communication model is shown in the figure:
The working process of the client Socket includes the following four basic steps:
- 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.
- Open the input/output stream connected to the Socket : use the getInputStream() method to obtain the input stream, and use the getOutputStream() method to obtain the output stream for data transmission
- Read/write operations on the Socket according to a certain protocol : read the information put into the line by the server through the input stream (but cannot read the information put into the line by itself), and write the information into the thread through the output stream.
- Close Socket : Disconnect the client from the server, releasing the line
The client program can use the Socket class to create objects, and at the same time it will automatically initiate a connection to the server . The constructor of Socket is:
- Socket(String host, int port) throws UnknownHostException, IOException: Initiate a TCP connection to the server (the domain name is host and the port number is port). If successful, create a Socket object, otherwise throw an exception.
- Socket(InetAddress address, int port) throws IOException: Initiate a connection according to 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
Socket s = new Socket(“192.168.40.165”,9999);
OutputStream out = s.getOutputStream();
out.write(" hello".getBytes());
s.close();
The working process of the server program includes the following four basic steps:
- Call ServerSocket(int port) : Create a server-side socket and bind it to the specified port. Used to monitor client requests.
- Call accept() : Listen for connection requests, if the client requests a connection, accept the connection and return the communication socket object.
- Call getOutputStream() and getInputStream() of the Socket class object : get the output stream and input stream, and start sending and receiving network data.
- Close the ServerSocket and Socket objects : the client access ends and the communication socket is closed
The server creates a ServerSocket object
ServerSocket ss = new ServerSocket(9999);
Socket s = ss.accept ();
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int num = in.read(buf);
String str = new String(buf,0,num);
System.out.println(s.getInetAddress().toString()+”:”+str);
s.close();
ss.close();
UDP network communication
Classes DatagramSocket and DatagramPacket implement network programs based on UDP protocol.
The UDP datagram is sent and received through the datagram socket DatagramSocket. The system does not guarantee that the UDP datagram will be delivered to the destination safely, nor can it be sure when it will arrive.
The DatagramPacket object encapsulates the UDP datagram, and the datagram contains the IP address and port number of the sending end and the IP address and port number of the receiving end.
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 courier package.
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 is chosen by the kernel.
public DatagramSocket(int port,InetAddress laddr)
Creates a datagram socket, binding it to the specified local address: the local port must be between 0 and 65535, inclusive. If the IP address is 0.0.0.0, the socket will be bound to a wildcard address, the IP address is chosen by the kernel
public void close()
Close this datagram socket:
public void send(DatagramPacket p)
Send a datagram packet from this socket. The information contained in the 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 packets from this socket. When this method returns, the DatagramPacket
's buffer is filled with the received data. The datagram packet also contains the sender's IP address and the port number on the sender's machine. This method blocks until a datagram is received. The length field of the datagram packet object contains the length of the received message. If the message is longer than the packet length, the message will be truncated.
public InetAddress getLocalAddress()
Get the local address to which the socket is bound.
public int getLocalPort()
Returns the port number on the local host to which this socket is bound.
public InetAddress getInetAddress()
Returns the address this socket is connected to. Returns null if the socket is not connected.
public int getPort()
Returns the port for this socket. Returns -1 if the socket is not connected.
Common methods of DatagramPacket packets
public DatagramPacket(byte[] buf,int length)
Construct DatagramPacket, used to receive data packets with 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 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 the machine to which this datagram was sent or received.
public int getPort()
returns the port number of a remote host to which this datagram is to be sent or received.
public byte[] getData()
Return the data buffer. The data received or to be sent starts at offset offset in the buffer and continues for length length.
public int getLength()
Returns the length of the data to be sent or received.
transfer process
Process:
1. DatagramSocket and DatagramPacket
2. Establish sender and receiver
3. Create data packet
4. Call Socket send and receive methods
5. Close Socket
The sender and receiver are two independent running programs
sender:
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
byte[] by = "hello,atguigu.com".getBytes();
DatagramPacket dp = new DatagramPacket(by, 0, by.length,
InetAddress.getByName("127.0.0.1"), 10000);
ds.send(dp);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ds != null)
ds.close();
}
Receiver
At the receiver, you need to specify the listening port.
DatagramSocket ds = null;
try {
ds = new DatagramSocket(10000);
byte[] by = new byte[1024];
DatagramPacket dp = new DatagramPacket(by, by.length);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str + "--" + dp.getAddress());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ds != null)
ds.close();
}