在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);
}
}
}