学习怎么学java网络编程绝非一蹴而就,需构建系统化认知路径。本路径基于真实企业开发需求与教学实践总结而成,分为六大阶段:
每阶段建议投入2–4周时间,辅以项目驱动学习。切忌“只看不练”——网络编程是实践性极强的领域。
特别提醒:很多学习者跳过基础直接写Socket,结果在SocketException: Connection reset或java.lang.OutOfMemoryError时束手无策——底层知识是排错的“指南针”。
理解协议是网络编程的“语言基础”:
建议使用telnet测试端口连通性:telnet www.xservx.com 80,观察响应报文,直观理解协议交互。
以下为最简服务器-客户端通信模型:
// Server.java import java.io.*; import java.net.*; public class Server { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8080); // 监听8080端口 Socket client = server.accept(); // 阻塞等待客户端连接 BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream(), true); String msg = in.readLine(); System.out.println("收到客户端消息: " + msg); out.println("Echo: " + msg); in.close(); out.close(); client.close(); server.close(); } } // Client.java public class Client { public static void main(String[] args) throws IOException { Socket socket = new Socket("localhost", 8080); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.println("Hello, Server!"); System.out.println("服务器响应: " + in.readLine()); socket.close(); } }
注意:此模型为单线程阻塞式,仅适合演示。生产环境需用线程池处理多客户端连接,否则一个客户端阻塞将导致其他客户端无法接入。
优化方案:为每个客户端分配独立线程:
import java.io.*; import java.net.*; import java.util.concurrent.*; public class MultiThreadServer { private static final int PORT = 8080; private static final int MAX_THREADS = 100; private final ExecutorService pool = new ThreadPoolExecutor( 5, MAX_THREADS, 60, TimeUnit.SECONDS, new LinkedBlockingQueue() ); public static void main(String[] args) throws IOException { new MultiThreadServer().start(); } public void start() throws IOException { ServerSocket server = new ServerSocket(PORT); System.out.println("服务器启动: 端口 " + PORT); while (true) { Socket client = server.accept(); // 阻塞等待连接 pool.execute(new ClientHandler(client)); } } private static class ClientHandler implements Runnable { private final Socket client; ClientHandler(Socket client) { this.client = client; } @Override public void run() { try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream(), true)) { String line; while ((line = in.readLine()) != null) { System.out.println("[客户端] " + line); out.println("Echo: " + line); if ("bye".equalsIgnoreCase(line)) break; } } catch (IOException e) { System.err.println("连接异常: " + e.getMessage()); } finally { try { client.close(); } catch (IOException ignored) {} } } } }
此方案解决了单线程阻塞问题,但仍有资源开销——每连接一线程,高并发下线程切换成本高。此时需引入NIO模型。
与传统Socket相比,NIO用少量线程管理大量连接,显著降低系统资源消耗。
import java.io.*; import java.net.*; import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; import java.util.*; public class NioServer { private static final int PORT = 9000; private static final int BUFFER_SIZE = 1024; private static final Charset CHARSET = StandardCharsets.UTF_8; public static void main(String[] args) throws IOException { new NioServer().start(); } public void start() throws IOException { Selector selector = Selector.open(); ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); // 必须设为非阻塞 serverChannel.bind(new InetSocketAddress(PORT)); serverChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("NIO服务器启动: 端口 " + PORT); while (selector.select() > 0) { // 阻塞直到有事件发生 Set<SelectionKey> keys = selector.selectedKeys(); for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext();) { SelectionKey key = it.next(); it.remove(); if (key.isAcceptable()) { acceptNewClient(key, selector); } else if (key.isReadable()) { handleRead(key); } } } } private void acceptNewClient(SelectionKey key, Selector selector) throws IOException { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel client = server.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_READ); System.out.println("新客户端连接: " + client.getRemoteAddress()); } private void handleRead(SelectionKey key) throws IOException { SocketChannel client = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); int bytesRead = client.read(buffer); if (bytesRead == -1) { client.close(); key.cancel(); System.out.println("客户端断开连接"); return; } buffer.flip(); byte[] data = new byte[buffer.remaining()]; buffer.get(data); String msg = new String(data, CHARSET); System.out.println("收到消息: " + msg); // 回写数据 buffer.clear(); buffer.put(("Echo: " + msg).getBytes(CHARSET)); buffer.flip(); client.write(buffer); } }
关键点:非阻塞模式下,accept()与read()不会卡住线程;Selector轮询机制实现单线程处理多连接。
适用于简单GET/POST请求,Java 6+内置支持:
import java.io.*; import java.net.*; import java.nio.charset.*; public class HttpUrlClient { public static void main(String[] args) throws IOException { // GET请求 URL getUrl = new URL("https://www.xservx.com/api/test"); HttpURLConnection conn = (HttpURLConnection) getUrl.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("User-Agent", "JavaClient/1.0"); int responseCode = conn.getResponseCode(); System.out.println("GET响应码: " + responseCode); try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line).append("\n"); } System.out.println("GET响应内容: " + response); } // POST请求(JSON数据) URL postUrl = new URL("https://api.example.com/login"); conn = (HttpURLConnection) postUrl.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); String jsonInput = "{"username":"admin","password":"123456"}"; try (OutputStream os = conn.getOutputStream()) { os.write(jsonInput.getBytes(StandardCharsets.UTF_8)); } responseCode = conn.getResponseCode(); System.out.println("POST响应码: " + responseCode); } }
局限:不支持HTTP/2、异步请求;复杂场景建议使用Java 11+的HttpClient。
支持同步/异步、HTTP/2、WebSocket等:
import java.net.http.*; import java.net.*; import java.time.Duration; public class ModernHttpClient { private static final HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(10)) .build(); public static void main(String[] args) throws Exception { // 同步GET请求 HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://www.xservx.com")) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("状态码: " + response.statusCode()); System.out.println("响应头: " + response.headers().firstValue("Content-Type")); // 异步POST请求(返回CompletableFuture) HttpRequest postRequest = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .POST(HttpRequest.BodyPublishers.ofString("{"id":123}")) .header("Content-Type", "application/json") .build(); client.sendAsync(postRequest, HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept(System.out::println) .join(); // 阻塞等待完成 } }
优势:API设计现代化、支持异步流式处理、自动HTTP/2多路复用。
无需安装Tomcat,直接在代码中嵌入:
import org.apache.catalina.*; import org.apache.catalina.startup.*; public class EmbeddedTomcat { public static void main(String[] args) throws Exception { Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); tomcat.addWebapp("/", new File("src/main/webapp").getAbsolutePath()); tomcat.start(); tomcat.getServer().await(); } }
需添加依赖(Maven):
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>10.1.18</version>
</dependency>
Netty是Java网络编程事实标准,支持高并发、低延迟:
// ServerHandler.java import io.netty.channel.*; public class ServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println("收到: " + msg); ctx.writeAndFlush("Echo: " + msg); // 写回响应 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } // Main.java import io.netty.bootstrap.*; import io.netty.channel.*; import io.netty.channel.nio.*; import io.netty.channel.socket.*; import io.netty.channel.socket.nio.*; public class NettyServer { public static void main(String[] args) { EventLoopGroup bossGroup = new NioEventLoopGroup(1); // 接收连接 EventLoopGroup workerGroup = new NioEventLoopGroup(); // 处理IO try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(new ServerHandler()); } }); ChannelFuture f = b.bind(9000).sync(); f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
Netty优势:事件驱动、零拷贝、内存池管理,适合构建RPC、游戏服务器等。
使用SSLSocket与SSLServerSocket实现HTTPS通信:
// 生成密钥库(使用keytool) # keytool -genkey -alias myserver -keyalg RSA -keysize 2048 -keystore server.jks // Server.java import javax.net.ssl.*; import java.io.*; public class SecureServer { public static void main(String[] args) throws Exception { System.setProperty("javax.net.ssl.keyStore", "server.jks"); System.setProperty("javax.net.ssl.keyStorePassword", "changeit"); SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(8443); while (true) { SSLSocket s = (SSLSocket) ss.accept(); new Thread(new SecureHandler(s)).start(); } } static class SecureHandler implements Runnable { private final SSLSocket s; SecureHandler(SSLSocket s) { this.s = s; } @Override public void run() { try (BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter out = new PrintWriter(s.getOutputStream(), true)) { out.println("Hello via TLS!"); } catch (IOException e) { e.printStackTrace(); } } } }
客户端需信任服务端证书(开发环境可使用自签名证书,生产环境建议CA签发)。
安全是持续过程,而非一次性配置——定期更新依赖库(如Netty)、关注CVE漏洞通报。
| 模型 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
| 一连接一线程 | 低并发(≤100) | 实现简单 | 线程切换开销大,内存消耗高 |
| 线程池+阻塞IO | 中等并发(≤1000) | 资源可控 | 连接数受限于线程池大小 |
| NIO+Selector | 高并发(≥10000) | 单线程管理多连接 | 编程复杂度高,需处理粘包/拆包 |
| AIO(Java 7+) | 极简异步IO | 事件回调式 | Windows支持好,Linux支持弱 |
为避免频繁创建/销毁连接,需使用连接池:
PoolingHttpClientConnectionManager示例:自定义Socket连接池核心逻辑:
import java.util.*; import java.net.*; public class SocketPool { private final String host; private final int port; private final int maxSize = 20; private final Queue<Socket> pool = new LinkedList<>(); public SocketPool(String host, int port) { this.host = host; this.port = port; } public synchronized Socket borrow() throws IOException { if (!pool.isEmpty()) { return pool.poll(); } return new Socket(host, port); } public synchronized void release(Socket socket) { if (pool.size() < maxSize) { pool.offer(socket); } else { try { socket.close(); } catch (IOException ignored) {} } } }
生产环境需增加健康检查(ping/pong)、超时回收、最大等待时间等机制。
需求:服务器接收任一客户端消息后,广播给所有在线客户端。
核心逻辑:
ConcurrentHashMap存储在线用户(key为用户名)关键代码片段:
// ServerHandler.java private static final Map<String, SocketChannel> clients = new ConcurrentHashMap<>(); public void broadcast(String message, SocketChannel exclude) { for (SocketChannel client : clients.values()) { if (client != exclude) { client.write(ByteBuffer.wrap((message + "\n").getBytes(StandardCharsets.UTF_8))); } } }
HTTP Range头实现断点续传:
Range: bytes=1024-(从1024字节开始下载)206 Partial Content + Content-Range: bytes 1024-10239/10240关键点:
RandomAccessFile定位文件读取位置Content-Range与Accept-Ranges: bytes此技术广泛应用于大文件下载、视频点播系统。
netstat -tuln | grep :8080是否显示监听状态sudo ufw disable0.0.0.0而非127.0.0.1以允许外网连接根本原因:读取后未清空Buffer或未处理完所有数据,导致Channel始终处于可读状态。
正确做法:
// 读取直到返回-1或0 while (channel.read(buffer) > 0) { buffer.flip(); process(buffer); buffer.compact(); } if (buffer.position() == 0) { key.interestOps(key.interestOps() & ~SelectionKey.OP_READ); }
常用策略:
\n(需转义处理)实测数据(1000请求,10并发):
| 协议 | 平均响应时间 | 吞吐量 |
|---|---|---|
| HTTP/1.1 | 85ms | 115 req/s |
| HTTPS/TLS1.2 | 98ms | 98 req/s |
| HTTP/2 over TLS | 72ms | 135 req/s |
结论:TLS握手有开销,但HTTP/2多路复用可抵消此差异,生产环境建议使用HTTP/2+TLS。
| 书名 | 作者 | 亮点 |
|---|---|---|
| 《Java网络编程(第4版)》 | Elliotte Rusty Harold | 经典理论结合代码,覆盖Socket到HTTP |
| 《Netty实战》 | Norman Maurer | Netty作者亲著,深入原理与架构 |
| 《高性能MySQL》 | Baron Schwartz | 虽为MySQL,但网络并发思想相通 |