在Java程式設計中,如何使伺服器允許連線到通訊端埠?
以下範例顯示如何使伺服器通過使用ServerSocket
類的server.accept()
方法和Socket
類的sock.getInetAddress()
方法來允許連線到通訊端埠:`1234
。
package com.yiibai;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class ConnectingSocket {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(12345);
while (true) {
System.out.println("Listening");
Socket sock = server.accept();
InetAddress addr = sock.getInetAddress();
System.out.println("Connection made to " + addr.getHostName() + " (" + addr.getHostAddress() + ")");
pause(5000);
sock.close();
}
} catch (IOException e) {
System.out.println("Exception detected: " + e);
}
}
private static void pause(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
}
}
}
上述程式碼範例將產生以下結果 -
Listening
Connection made to 127.0.0.1 (127.0.0.1)
Listening
用戶端程式碼參考如下 -
package com.yiibai;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class SocketClient {
public static void main(String[] args) {
try {
//InetAddress addr = InetAddress.getByName("127.0.0.1");
Socket theSocket = new Socket("127.0.0.1", 12345);
System.out.println("Connected to " + theSocket.getInetAddress() + " on port " + theSocket.getPort()
+ " from port " + theSocket.getLocalPort() + " of " + theSocket.getLocalAddress());
} catch (UnknownHostException e) {
System.err.println("I can't find " + e);
} catch (SocketException e) {
System.err.println("Could not connect to " + e);
} catch (IOException e) {
System.err.println(e);
}
}
}