我正在做一個簡單的練習來理解套接字和服務器套接字。當myServerSocket = new ServerSocket(0)
端口被隨機分配到該插座。我想知道如何設置客戶端連接到該端口。如果客戶端隨機分配,客戶端如何查找偵聽端口?Java客戶端/服務器套接字端口分配
下面是代碼從服務器和客戶端類的代碼片段:
服務器:
public static void main(String[] args) {
try {
// First we create a server socket and bind it to a random port.
ServerSocket myServerSocket = new ServerSocket(0);
// wait for an incoming connection...
System.out.println("Server is waiting for an incoming connection on host="
+ InetAddress.getLocalHost().getCanonicalHostName()
+ " port=" + myServerSocket.getLocalPort());
Socket skt = myServerSocket.accept();
客戶:
public static void main(String[] args) {
// create a socket and bind it to the host/port server is listening on.
String host;
int port;
if(args.length==0) {
host = "localhost";
port = 9999;
} else {
host = args[0];
String portStr = args[1];
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
System.out.println("Whoops, invalid port number. Will default to 9999");
port = 9999;
}
}
客戶端必須知道服務器偵聽的確切端口號 – 2015-02-10 20:43:12
上述內容。否則某種類型的端口掃描,但我猜測,除非使用一些啓發式(或隨機端口函數的最小值[即範圍]收緊),否則需要很長時間才能通過所有端口。 – noumenal 2015-02-10 20:47:05