network programming

Published 2026-07-29 09:23 Updated 2026-10-13 17:14 842 words 5 min read ... Page views AI-reviewed An AI proof-read this post, but it still deserves a careful read. AI-rewritten Someone else wrote the original; AI helped me rewrite and polish it.

AI-reviewed An AI proof-read this post, but it still deserves a careful read.

This article introduces the characteristics and application scenarios of TCP and UDP network protocols: TCP is connection-oriented and reliable transmission, and is suitable for scenarios with high data integrity requirements;UDP has no connection, low overhead, and is suitable for applications that tolerate packet loss. It then explains the programming models of TCP and UDP, including the use of core classes such as InetAddress, Socket, ServerSocket, DatagramSocket, and DatagramPacket, as well as the communication process between client and server. Finally, I mentioned the role of URLs and the use of byte streams and buffers when downloading network files to improve performance.

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 Used to represent the IP address and its corresponding host information.

  • localhost is the host name pointing to the local machine.
  • 127.0.0.1 is the IPv4 loopback address.

Client and server model

TCP usually adopts a client-server model. server through ServerSocket Listening port, used by client Socket Proactively initiate a connection.

image-001
image-001
image-002
image-002

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() The current thread is blocked 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 Used to send and receive UDP datagrams, and can be understood as the communication endpoint for the program 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() It 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, you should use byte streams and read and write in batches through buffers to avoid unnecessary performance losses caused by byte-by-byte processing.

Written by AI-rewritten

If you enjoyed this, leave a comment~

Loading...