Java 网络编程
核对 java.net 中 TCP 与 UDP 协议支持、Socket 客户端与 ServerSocket 服务端握手流程、ServerSocket/Socket/InetAddress 构造与核心方法、Greeting 双向通信示例及本地回环实测。
学完这一章,你能够
- 核对 java.net 中 TCP 与 UDP 协议支持、Socket 客户端与 ServerSocket 服务端握手流程、ServerSocket/Socket/InetAddress 构造与核心方法、Greeting 双向通信示例及本地回环实测。
java.net 协议支持与通信主题
网络编程用于让多台联网主机或同一主机上的多个进程通过网络协议交换数据。`java.net` 包封装了底层通信细节,重点支持两类传输层协议:一是面向连接、提供可靠有序字节流传输的 TCP(传输控制协议,常与 IP 合称 TCP/IP);二是无连接、基于独立数据报传输的 UDP(用户数据报协议,开销低但不保证到达与顺序,适合允许少量丢包的实时场景)。学习重点包括基于 TCP/UDP 的 Socket 编程以及 `URL`/`URI` 资源地址解析。
TCP Socket 握手生命周期
在 Java 中,`java.net.ServerSocket` 负责服务端端口监听,`java.net.Socket` 代表通信两端的流套接字。一次典型 TCP 连接经历五步:服务端实例化 `ServerSocket` 绑定监听端口;调用 `accept()` 阻塞等待客户端接入;客户端实例化 `Socket(host, port)` 发起连接请求;三次握手成功后客户端获得已连接 `Socket`;服务端 `accept()` 返回对应的独立 `Socket` 引用。连接建立后,双方通过各自的输入流与输出流(客户端输出流对接服务端输入流,反之亦然)进行全双工双向读写。
ServerSocket、Socket 与 InetAddress 核心 API
`ServerSocket` 提供 4 个构造方法(支持指定端口、连接队列 `backlog`、绑定网卡 `InetAddress` 或无参创建未绑定实例再调用 `bind()`),若构造未抛异常则表明已成功监听;常用方法包括 `getLocalPort()`、`accept()`、`setSoTimeout(int)`(超时触发 `SocketTimeoutException`)与 `bind(SocketAddress, int)`。
`Socket` 提供 5 个构造方法(除无参未连接构造外,其余在返回前即实际发起 TCP 连接),客户端与服务端返回的 `Socket` 均可调用 `connect`、`getInetAddress`、`getPort`、`getLocalPort`、`getRemoteSocketAddress`、`getInputStream`、`getOutputStream` 与 `close`。`InetAddress` 用于表示 IP 地址与主机名映射,提供 `getByAddress`、`getByName`、`getHostAddress`、`getHostName`、`getLocalHost` 与 `toString` 等工具方法。
Greeting 客户端/服务端示例与本地回环实测
经典的 `GreetingServer` 与 `GreetingClient` 通过 `DataInputStream.readUTF()` 和 `DataOutputStream.writeUTF()` 完成一次问答通信:先编译并启动服务端监听指定端口,再在另一终端启动客户端连接 `localhost` 与相同端口。需特别注意:若服务端类继承了 `Thread`,启动独立后台线程应调用 `t.start()` 而非直接调用 `t.run()`(直接调用 `run()` 仅在当前主线程同步执行)。本站 OpenJDK 8 离线实验在 `127.0.0.1` 临时端口上真实启动了后台守护线程 `ServerSocket(0)`,完整验证了 TCP 双向收发、无参 `bind`/`connect`、`SO_TIMEOUT` 超时异常、`InetAddress` 与 `URL`/`URI` 解析,以及本地回环 UDP `DatagramSocket` 收发。
ServerSocket 构造方法参考
| 序号 | 构造方法与说明 |
|---|---|
| 1 | public ServerSocket(int port) throws IOException:创建并绑定到指定本地端口的服务器套接字(传 0 表示由系统分配临时空闲端口)。 |
| 2 | public ServerSocket(int port, int backlog) throws IOException:指定监听端口与最大挂起连接队列长度 backlog。 |
| 3 | public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException:指定端口、队列长度及绑定的本地网卡 IP 地址。 |
| 4 | public ServerSocket() throws IOException:创建尚未绑定的服务器套接字,后续需配合 bind() 使用。 |
ServerSocket 常用方法参考
| 序号 | 方法签名与说明 |
|---|---|
| 1 | public int getLocalPort():返回该服务器套接字正在监听的本地端口号。 |
| 2 | public Socket accept() throws IOException:阻塞侦听并接受一个客户端连接,返回通信 Socket。 |
| 3 | public void setSoTimeout(int timeout):设置 accept() 的阻塞超时时间(毫秒),超时抛出 SocketTimeoutException。 |
| 4 | public void bind(SocketAddress endpoint, int backlog):将未绑定的 ServerSocket 绑定到指定地址端口与队列上限。 |
Socket 构造方法参考
| 序号 | 构造方法与说明 |
|---|---|
| 1 | public Socket(String host, int port) throws UnknownHostException, IOException:创建流套接字并立即连接指定主机名和端口。 |
| 2 | public Socket(InetAddress address, int port) throws IOException:创建流套接字并连接到指定 IP 地址与端口。 |
| 3 | public Socket(String host, int port, InetAddress localAddr, int localPort) throws IOException:连接远程主机端口并同时指定本地出口地址与端口。 |
| 4 | public Socket(InetAddress address, int port, InetAddress localAddr, int localPort) throws IOException:通过 IP 地址连接远程端点并绑定指定本地地址端口。 |
| 5 | public Socket():创建未连接套接字,随后可配置选项并调用 connect(endpoint, timeout)。 |
Socket 常用方法参考
| 序号 | 方法签名与说明 |
|---|---|
| 1 | public void connect(SocketAddress endpoint, int timeout) throws IOException:在指定毫秒超时内将未连接套接字接入服务器。 |
| 2 | public InetAddress getInetAddress():返回套接字所连接对端的 IP 地址。 |
| 3 | public int getPort():返回套接字所连接的远程端口号。 |
| 4 | public int getLocalPort():返回本端套接字绑定使用的本地端口号。 |
| 5 | public SocketAddress getRemoteSocketAddress():返回远程端点地址,未连接时返回 null。 |
| 6 | public InputStream getInputStream() throws IOException:返回用于读取对端数据的输入流。 |
| 7 | public OutputStream getOutputStream() throws IOException:返回用于向对端发送数据的输出流。 |
| 8 | public void close() throws IOException:关闭此套接字及其关联的输入/输出流。 |
InetAddress 常用方法参考
| 序号 | 方法签名与说明 |
|---|---|
| 1 | static InetAddress getByAddress(byte[] addr):根据原始 IPv4/IPv6 字节数组构造 InetAddress。 |
| 2 | static InetAddress getByAddress(String host, byte[] addr):使用显式主机名与原始 IP 字节构造 InetAddress(不触发 DNS)。 |
| 3 | static InetAddress getByName(String host):解析主机名或字面 IP 地址并返回 InetAddress。 |
| 4 | String getHostAddress():返回点分十进制或冒号十六进制文本格式的 IP 地址。 |
| 5 | String getHostName():获取此 IP 地址对应的主机名。 |
| 6 | static InetAddress getLocalHost():返回本机主机的 InetAddress。 |
| 7 | String toString():返回形如 主机名/IP地址 的字符串表示。 |
运行 Java 8 本地回环 TCP Socket 通信、超时控制、InetAddress/URL 解析与 UDP 数据报实测
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
public class ExploreNetworking {
private static String escapeJson(String s) {
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
else sb.append(c);
}
}
return sb.append('"').toString();
}
private static String toJson(Object obj) {
if (obj == null) return "null";
if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
if (obj instanceof String) return escapeJson((String) obj);
if (obj instanceof List<?>) {
StringBuilder sb = new StringBuilder("[");
List<?> list = (List<?>) obj;
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(toJson(list.get(i)));
}
return sb.append("]").toString();
}
if (obj instanceof Map<?, ?>) {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
if (!first) sb.append(", ");
first = false;
sb.append(escapeJson(String.valueOf(e.getKey()))).append(": ").append(toJson(e.getValue()));
}
return sb.append("}").toString();
}
return escapeJson(String.valueOf(obj));
}
private static Map<String, Object> makeCase(String name, String summary, Object expected, Object actual) {
Map<String, Object> c = new LinkedHashMap<String, Object>();
c.put("name", name);
c.put("summary", summary);
c.put("expected", expected);
c.put("actual", actual);
c.put("passed", expected.equals(actual));
return c;
}
public static void main(String[] args) throws Exception {
List<Map<String, Object>> cases = new ArrayList<Map<String, Object>>();
// Case 1: Real local loopback TCP ServerSocket(0) + Socket Greeting exchange
{
final AtomicReference<String> serverReceived = new AtomicReference<String>("");
final AtomicReference<Throwable> serverErr = new AtomicReference<Throwable>(null);
ServerSocket serverSocket = new ServerSocket(0, 10, InetAddress.getLoopbackAddress());
try {
serverSocket.setSoTimeout(5000);
final int port = serverSocket.getLocalPort();
Thread serverThread = new Thread(new Runnable() {
@Override
public void run() {
try (Socket conn = serverSocket.accept()) {
conn.setSoTimeout(5000);
DataInputStream in = new DataInputStream(conn.getInputStream());
String msg = in.readUTF();
serverReceived.set(msg);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeUTF("ACK:" + msg + "|Goodbye!");
out.flush();
} catch (Throwable t) {
serverErr.set(t);
}
}
});
serverThread.setDaemon(true);
serverThread.start();
String clientReply;
boolean remoteMatchesPort;
boolean localPortValid;
boolean remoteAddrNonNull;
try (Socket client = new Socket("127.0.0.1", port)) {
client.setSoTimeout(5000);
remoteMatchesPort = (client.getPort() == port);
localPortValid = (client.getLocalPort() > 0);
remoteAddrNonNull = (client.getRemoteSocketAddress() != null && "127.0.0.1".equals(client.getInetAddress().getHostAddress()));
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeUTF("Hello from client");
out.flush();
DataInputStream in = new DataInputStream(client.getInputStream());
clientReply = in.readUTF();
}
serverThread.join(3000);
if (serverErr.get() != null) {
throw new RuntimeException(serverErr.get());
}
Map<String, Object> expected = new LinkedHashMap<String, Object>();
expected.put("server_received", "Hello from client");
expected.put("client_reply", "ACK:Hello from client|Goodbye!");
expected.put("remote_port_matches", true);
expected.put("local_port_positive", true);
expected.put("remote_loopback_ok", true);
Map<String, Object> actual = new LinkedHashMap<String, Object>();
actual.put("server_received", serverReceived.get());
actual.put("client_reply", clientReply);
actual.put("remote_port_matches", remoteMatchesPort);
actual.put("local_port_positive", localPortValid);
actual.put("remote_loopback_ok", remoteAddrNonNull);
cases.add(makeCase(
"tcp_loopback_greeting_exchange",
"验证本地回环 ServerSocket(0) 与 Socket 通过 DataInputStream/DataOutputStream 完成双向 TCP 握手与通信",
expected,
actual
));
} finally {
serverSocket.close();
}
}
// Case 2: Unbound ServerSocket.bind(), unbound Socket.connect(addr, timeout), and ServerSocket.setSoTimeout() timeout
{
ServerSocket unboundServer = new ServerSocket();
boolean timedOut = false;
boolean connectedViaBind = false;
try {
unboundServer.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 8);
int boundPort = unboundServer.getLocalPort();
// Verify unbound Socket connect()
final AtomicReference<Boolean> accepted = new AtomicReference<Boolean>(false);
Thread acceptor = new Thread(new Runnable() {
@Override
public void run() {
try (Socket s = unboundServer.accept()) {
accepted.set(s.isConnected());
} catch (IOException ignored) {
}
}
});
acceptor.setDaemon(true);
unboundServer.setSoTimeout(5000);
acceptor.start();
try (Socket client = new Socket()) {
boolean beforeNull = (client.getRemoteSocketAddress() == null);
client.connect(new InetSocketAddress("127.0.0.1", boundPort), 3000);
connectedViaBind = beforeNull && client.isConnected() && client.getPort() == boundPort;
}
acceptor.join(3000);
// Verify SO_TIMEOUT triggers SocketTimeoutException
unboundServer.setSoTimeout(40);
try {
unboundServer.accept();
} catch (SocketTimeoutException ex) {
timedOut = true;
}
} finally {
unboundServer.close();
}
Map<String, Object> expected = new LinkedHashMap<String, Object>();
expected.put("unbound_bind_and_connect_ok", true);
expected.put("so_timeout_throws_ste", true);
Map<String, Object> actual = new LinkedHashMap<String, Object>();
actual.put("unbound_bind_and_connect_ok", connectedViaBind);
actual.put("so_timeout_throws_ste", timedOut);
cases.add(makeCase(
"serversocket_bind_connect_and_timeout",
"验证无参 ServerSocket.bind()、无参 Socket.connect(host, timeout) 与 setSoTimeout() 触发 SocketTimeoutException",
expected,
actual
));
}
// Case 3: InetAddress methods (getByAddress, getByName, getHostAddress, getHostName, getLocalHost, toString) & offline URL/URI parsing
{
InetAddress byBytes = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
InetAddress byHostBytes = InetAddress.getByAddress("loopback.local", new byte[]{127, 0, 0, 1});
InetAddress byName = InetAddress.getByName("127.0.0.1");
InetAddress localHost = InetAddress.getLocalHost();
URL url = new URL("https://example.org:8443/docs/net?proto=tcp#socket");
URI uri = url.toURI();
Map<String, Object> expected = new LinkedHashMap<String, Object>();
expected.put("by_bytes_ip", "127.0.0.1");
expected.put("by_host_bytes_name", "loopback.local");
expected.put("by_host_bytes_tostring", "loopback.local/127.0.0.1");
expected.put("by_name_ip", "127.0.0.1");
expected.put("local_host_nonempty", true);
expected.put("url_parts", Arrays.asList("https", "example.org", "8443", "/docs/net", "proto=tcp", "socket"));
Map<String, Object> actual = new LinkedHashMap<String, Object>();
actual.put("by_bytes_ip", byBytes.getHostAddress());
actual.put("by_host_bytes_name", byHostBytes.getHostName());
actual.put("by_host_bytes_tostring", byHostBytes.toString());
actual.put("by_name_ip", byName.getHostAddress());
actual.put("local_host_nonempty", localHost.getHostAddress() != null && !localHost.getHostAddress().isEmpty());
actual.put("url_parts", Arrays.asList(
url.getProtocol(),
url.getHost(),
String.valueOf(url.getPort()),
url.getPath(),
url.getQuery(),
uri.getFragment()
));
cases.add(makeCase(
"inetaddress_and_url_parsing",
"验证 InetAddress 常用解析方法及离线 URL/URI 协议、主机、端口、路径与查询串解析",
expected,
actual
));
}
// Case 4: Real local loopback UDP DatagramSocket exchange
{
DatagramSocket receiver = new DatagramSocket(0, InetAddress.getLoopbackAddress());
DatagramSocket sender = new DatagramSocket(0, InetAddress.getLoopbackAddress());
try {
receiver.setSoTimeout(3000);
byte[] payload = "UDP-PING".getBytes(StandardCharsets.UTF_8);
DatagramPacket outPkt = new DatagramPacket(
payload, payload.length, InetAddress.getLoopbackAddress(), receiver.getLocalPort()
);
sender.send(outPkt);
byte[] buf = new byte[64];
DatagramPacket inPkt = new DatagramPacket(buf, buf.length);
receiver.receive(inPkt);
String received = new String(inPkt.getData(), 0, inPkt.getLength(), StandardCharsets.UTF_8);
Map<String, Object> expected = new LinkedHashMap<String, Object>();
expected.put("udp_received", "UDP-PING");
expected.put("sender_port_matches", true);
Map<String, Object> actual = new LinkedHashMap<String, Object>();
actual.put("udp_received", received);
actual.put("sender_port_matches", inPkt.getPort() == sender.getLocalPort());
cases.add(makeCase(
"udp_loopback_datagram_exchange",
"验证 java.net.DatagramSocket 与 DatagramPacket 在本地回环上的无连接 UDP 数据报收发",
expected,
actual
));
} finally {
sender.close();
receiver.close();
}
}
Map<String, Object> root = new LinkedHashMap<String, Object>();
root.put("version", "OpenJDK " + System.getProperty("java.version"));
root.put("cases", cases);
System.out.println(toJson(root));
}
}
- 验证本地 127.0.0.1 临时端口 ServerSocket/Socket 双向 UTF 通信、无参 bind/connect 与 SO_TIMEOUT 超时异常、InetAddress 与 URL/URI 离线解析,以及本地回环 UDP DatagramSocket 收发。
所需环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
当前源码 SHA256:325fafd5b0e587f626272d7fb985c3e94860f41b1fe453736c929cc44c858c34
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
ZIP SHA256:eee3ff2ddf27bd4820a3ec2d4f54a9376e1f65c920c2c1a7a10315b15872b396
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 GreetingServer 示例中,ServerSocket 构造时传入端口 0 有什么作用?为什么调用 Thread 子类时应写 t.start() 而不是 t.run()?
展开参考解答
传入端口 0 表示请求操作系统自动分配一个当前空闲的临时端口(随后用 getLocalPort() 获取),常用于自动化测试避免端口冲突;t.start() 才会向 JVM 申请新线程并异步执行 run(),直接调用 t.run() 只是在当前线程内做普通同步方法调用。