java如何编写端口
Java 编写端口的基本方法
在 Java 中,编写端口通常涉及使用 java.net 包中的类来创建服务器或客户端程序,监听或连接到指定端口。以下是常见场景的实现方法。
创建 TCP 服务器监听端口
使用 ServerSocket 类监听指定端口,等待客户端连接:
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) {
int port = 8080; // 指定端口号
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server listening on port " + port);
Socket clientSocket = serverSocket.accept(); // 等待客户端连接
System.out.println("Client connected: " + clientSocket.getInetAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
}
创建 TCP 客户端连接端口
使用 Socket 类连接到指定服务器的端口:
import java.net.Socket;
public class TcpClient {
public static void main(String[] args) {
String serverAddress = "localhost";
int port = 8080;
try (Socket socket = new Socket(serverAddress, port)) {
System.out.println("Connected to server on port " + port);
} catch (Exception e) {
e.printStackTrace();
}
}
}
创建 UDP 服务器监听端口
使用 DatagramSocket 监听 UDP 端口:
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetAddress;
public class UdpServer {
public static void main(String[] args) {
int port = 9090;
try (DatagramSocket socket = new DatagramSocket(port)) {
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("Received: " + message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
创建 UDP 客户端发送数据到端口
使用 DatagramSocket 发送数据到指定 UDP 端口:
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetAddress;
public class UdpClient {
public static void main(String[] args) {
String serverAddress = "localhost";
int port = 9090;
try (DatagramSocket socket = new DatagramSocket()) {
String message = "Hello UDP Server";
byte[] data = message.getBytes();
DatagramPacket packet = new DatagramPacket(
data,
data.length,
InetAddress.getByName(serverAddress),
port
);
socket.send(packet);
System.out.println("Message sent to port " + port);
} catch (Exception e) {
e.printStackTrace();
}
}
}
检查端口是否可用
在绑定端口前,可以检查端口是否被占用:

import java.net.ServerSocket;
public class PortChecker {
public static boolean isPortAvailable(int port) {
try (ServerSocket ignored = new ServerSocket(port)) {
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
int port = 8080;
System.out.println("Port " + port + " available: " + isPortAvailable(port));
}
}
注意事项
- 端口范围:有效端口号为 0-65535,通常 0-1023 为系统保留端口。
- 权限问题:在 Linux/Unix 上绑定 1024 以下端口可能需要管理员权限。
- 异常处理:端口被占用或无权访问时会抛出
IOException,需妥善处理。
通过以上方法,可以灵活实现 Java 中的端口操作。






