network programming
TCP and UDP protocols
TCP protocol
TCP is a connection-oriented and reliable transmission protocol. A connection needs to be established before communication, and mechanisms such as confirmation, retransmission, and sorting are used to ensure that the data arrives as complete and orderly as possible.
UDP protocol
UDP is a connectionless protocol for datagrams. It does not guarantee the arrival of data or the order of arrival, but the protocol overhead is small and suitable for scenarios where a small amount of packet loss can be tolerated or reliability is guaranteed by the application layer itself.
Choosing TCP or UDP should be based on reliability, latency, throughput and service characteristics, and cannot be judged based on network conditions alone.
TCP programming
InetAddress class
InetAddress is used to represent the IP address and its corresponding host information.
localhostis the host name pointing to the machine.127.0.0.1is an IPv4 loopback address.
Client and server model
TCP usually adopts a client-server model. The server listens on the port through ServerSocket, and the client uses Socket to proactively initiate a connection.


TCP server
public class TestServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(7000);
Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(
socket.getOutputStream(), true)) {
System.out.println("有客户端连接了服务器");
System.out.println(reader.readLine());
writer.println("1 + 1 的结果是 2");
} catch (IOException e) {
e.printStackTrace();
}
}
}accept() will block the current thread until a client establishes a connection. After the connection is successful, the server receives data through the input stream of the socket and sends data through the output stream.
TCP client
public class TestClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 7000);
PrintWriter writer = new PrintWriter(
socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()))) {
writer.println("我是客户端,1 + 1 = ?");
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}Both the client and the server can read and write data at the same time. When implementing two-way chat, it is usually necessary to handle sending and receiving operations separately to prevent one party from continuously blocking and preventing communication from continuing.
UDP Programming
DatagramSocket
DatagramSocket is used to send and receive UDP datagrams, and can be understood as the communication endpoint for programs to send and receive datagrams.
DatagramPacket
DatagramPacket represents a datagram. When sending, you need to encapsulate the data, target address and target port; when receiving, you need to prepare a byte array in advance as a receive buffer.
A-end program
public class ATestUDP {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket(7004)) {
byte[] sendData = "hello".getBytes(StandardCharsets.UTF_8);
DatagramPacket sendPacket = new DatagramPacket(
sendData,
sendData.length,
InetAddress.getByName("localhost"),
7003
);
socket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(
receiveData,
receiveData.length
);
socket.receive(receivePacket);
String message = new String(
receivePacket.getData(),
0,
receivePacket.getLength(),
StandardCharsets.UTF_8
);
System.out.println(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}B-end program
public class BTestUDP {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket(7003)) {
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(
receiveData,
receiveData.length
);
socket.receive(receivePacket);
String message = new String(
receivePacket.getData(),
0,
receivePacket.getLength(),
StandardCharsets.UTF_8
);
System.out.println(message);
byte[] sendData = "我收到了".getBytes(StandardCharsets.UTF_8);
DatagramPacket sendPacket = new DatagramPacket(
sendData,
sendData.length,
receivePacket.getAddress(),
receivePacket.getPort()
);
socket.send(sendPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
}receive() blocks until a datagram is received. The basic unit of UDP sending and receiving each time is a complete datagram.
URL
URLs are uniform resource locators used to locate resources on the network. Common structures can be expressed as:
协议://主机:端口/路径?参数名=参数值&参数名=参数值
Ports, paths, and query parameters may not all exist.
URL Programming
Read web content
public class TestURL {
public static void main(String[] args) {
try {
URL url = new URL("https://www.baidu.com/");
URLConnection connection = url.openConnection();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
connection.getInputStream(),
StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}Download Network Files
public class URLDownload {
public static void main(String[] args) {
String address = "https://copyright.bdstatic.com/vcg/creative/"
+ "65e11b3d96ac8f9b293b2d3486b7c422.jpg@wm_1,"
+ "k_cGljX2JqaHdh dGVyLmpwZw==".replace(" ", "");
try {
URL url = new URL(address);
URLConnection connection = url.openConnection();
try (BufferedInputStream input = new BufferedInputStream(
connection.getInputStream());
BufferedOutputStream output = new BufferedOutputStream(
new FileOutputStream("d:/lession/java2601/test/a.jpg"))) {
byte[] buffer = new byte[8192];
int length;
while ((length = input.read(buffer)) != -1) {
output.write(buffer, 0, length);
}
output.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}When downloading binary files, byte streams should be used and read and write in batches through buffers to avoid unnecessary performance loss caused by byte-by-byte processing.
If you enjoyed this, leave a comment~