您的位置:首页 >Linux系统Java如何进行网络编程
发布于2026-05-02 阅读(0)
扫一扫,手机访问
想在Linux环境下用Ja va搞定网络通信?这事儿其实没想象中那么复杂。核心就在于用好Ja va标准库里的那套网络API,特别是ja va.net包下的那些工具。下面,咱们就通过几个典型的场景和代码示例,来快速上手。
Socket编程是网络通信的基石,理解它,就等于拿到了入门钥匙。
客户端的工作很明确:找到服务器,建立连接,然后收发数据。用Socket类就能轻松实现。
import ja va.io.*;
import ja va.net.*;
public class Client {
public static void main(String[] args) {
// 使用try-with-resources确保资源自动关闭
try (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!");
// 等待并打印服务器的回应
String response = in.readLine();
System.out.println("Server response: " + response);
} catch (UnknownHostException e) {
System.err.println("找不到主机: localhost。");
e.printStackTrace();
} catch (IOException e) {
System.err.println("连接到 localhost 时出现I/O错误。");
e.printStackTrace();
}
}
}
服务器则要沉得住气,它用ServerSocket在指定端口上“蹲点”,等待客户端上门。
import ja va.io.*;
import ja va.net.*;
public class Server {
public static void main(String[] args) {
// 在8080端口开启监听
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("服务器已在端口 8080 上启动监听...");
// 持续运行,处理源源不断的客户端连接
while (true) {
try (Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
// 读取客户端发来的消息
String inputLine = in.readLine();
System.out.println("收到客户端消息: " + inputLine);
// 给客户端一个回应
out.println("Hello, Client!");
} catch (IOException e) {
System.err.println("处理客户端连接时发生异常。");
e.printStackTrace();
}
}
} catch (IOException e) {
System.err.println("无法在端口 8080 上启动监听。");
e.printStackTrace();
}
}
}
如果你的目标是访问Web资源(比如抓取网页内容),那么URL和URLConnection这套组合拳会更顺手。
import ja va.io.*;
import ja va.net.*;
public class URLClient {
public static void main(String[] args) {
try {
// 指定目标URL
URL url = new URL("http://example.com");
// 打开连接
URLConnection connection = url.openConnection();
// 读取返回的数据流
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException e) {
System.err.println("URL格式错误: http://example.com");
e.printStackTrace();
} catch (IOException e) {
System.err.println("从URL读取数据时发生I/O错误。");
e.printStackTrace();
}
}
}
当连接数成百上千时,传统的阻塞式I/O可能会力不从心。这时,就该Ja va NIO登场了。它通过选择器(Selector)机制,能用单个线程管理多个通道,特别适合高性能服务器。
import ja va.io.IOException;
import ja va.net.InetSocketAddress;
import ja va.nio.ByteBuffer;
import ja va.nio.channels.SelectionKey;
import ja va.nio.channels.Selector;
import ja va.nio.channels.ServerSocketChannel;
import ja va.nio.channels.SocketChannel;
import ja va.util.Iterator;
import ja va.util.Set;
public class NIOServer {
public static void main(String[] args) throws IOException {
// 1. 打开选择器
Selector selector = Selector.open();
// 2. 创建服务器通道并绑定端口
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8080));
// 3. 设置为非阻塞模式,并注册到选择器,关注“接受连接”事件
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
// 4. 阻塞,直到有感兴趣的事件发生
selector.select();
Set selectedKeys = selector.selectedKeys();
Iterator iter = selectedKeys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
if (key.isAcceptable()) {
// 有新的连接到来
register(selector, serverSocketChannel);
}
if (key.isReadable()) {
// 有通道可读,处理数据
readDataFromSocket(key);
}
iter.remove(); // 处理完后移除当前key
}
}
}
private static void register(Selector selector, ServerSocketChannel serverSocketChannel) throws IOException {
// 接受客户端连接,并将其注册到选择器,关注“读”事件
SocketChannel client = serverSocketChannel.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}
private static void readDataFromSocket(SelectionKey key) throws IOException {
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = client.read(buffer);
if (bytesRead == -1) {
// 连接已关闭
client.close();
} else if (bytesRead > 0) {
buffer.flip();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
String message = new String(data).trim();
System.out.println("收到消息: " + message);
}
}
}
好了,以上就是Ja va在Linux平台上进行网络编程的几个核心套路。从最基础的Socket对话,到便捷的URL资源访问,再到应对高性能挑战的NIO模型,各有各的适用场景。简单来说,常规需求用前两种方法就足够了;但如果你在构建需要同时处理海量连接的服务器,那么深入研究NIO,绝对是值得的。关键在于根据你的实际项目需求,挑选最合适的那把“工具”。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9