Java网络编程基础详解
什么是网络编程
网络编程是编写可以通过网络进行通信的应用程序。Java提供了丰富的网络编程API,支持TCP和UDP协议。
InetAddress类
InetAddress类用于表示IP地址。
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressDemo {
public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("本地主机: " + localHost);
System.out.println("主机名: " + localHost.getHostName());
System.out.println("IP地址: " + localHost.getHostAddress());
InetAddress byName = InetAddress.getByName("www.baidu.com");
System.out.println("百度IP: " + byName.getHostAddress());
InetAddress[] allByName = InetAddress.getAllByName("www.google.com");
for (InetAddress addr : allByName) {
System.out.println("Google IP: " + addr.getHostAddress());
}
InetAddress loopback = InetAddress.getLoopbackAddress();
System.out.println("回环地址: " + loopback);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
URL类
URL类用于表示统一资源定位符。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class URLDemo {
public static void main(String[] args) {
try {
URL url = new URL("https://www.baidu.com");
System.out.println("协议: " + url.getProtocol());
System.out.println("主机: " + url.getHost());
System.out.println("端口: " + url.getPort());
System.out.println("路径: " + url.getPath());
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
String line;
int lineCount = 0;
while ((line = reader.readLine()) != null && lineCount < 5) {
System.out.println(line);
lineCount++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Socket编程
TCP Socket客户端
import java.io.*;
import java.net.Socket;
public class TcpClientDemo {
public static void main(String[] args) {
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("服务器响应: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
TCP Socket服务器
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("服务器启动,等待连接...");
while (true) {
Socket client = serverSocket.accept();
System.out.println("客户端连接: " + client.getInetAddress());
new Thread(() -> {
try (BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(
client.getOutputStream(), true)) {
String message = in.readLine();
System.out.println("收到消息: " + message);
out.println("Echo: " + message);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
UDP Socket
UDP客户端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClientDemo {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket()) {
String message = "Hello UDP Server";
byte[] data = message.getBytes();
InetAddress serverAddr = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(
data, data.length, serverAddr, 9999);
socket.send(packet);
byte[] buffer = new byte[1024];
DatagramPacket response = new DatagramPacket(buffer, buffer.length);
socket.receive(response);
String responseMsg = new String(response.getData(), 0, response.getLength());
System.out.println("服务器响应: " + responseMsg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
UDP服务器
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpServerDemo {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket(9999)) {
System.out.println("UDP服务器启动...");
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("收到消息: " + message);
byte[] responseData = ("Echo: " + message).getBytes();
DatagramPacket response = new DatagramPacket(
responseData, responseData.length,
packet.getAddress(), packet.getPort());
socket.send(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
网络编程最佳实践
- 设置合理的超时时间
- 使用try-with-resources管理网络资源
- 处理网络异常
- 考虑使用NIO提高性能
- 注意网络安全
总结
Java网络编程提供了丰富的API来处理网络通信。理解Socket编程和URL操作,能帮助你构建网络应用程序。