【发布时间】:2012-05-10 18:31:37
【问题描述】:
所以我有一个在桌面应用程序中使用 Socket 和 ServerSocket 的 TCP/IP 服务器/客户端模型(应该在网络中玩的游戏)。
我需要获取服务器远程 IP 地址,以便客户端应用程序可以在打开的特定端口上打开的服务器应用程序连接到它。
public class ServerConnection {
private int PORT = 8100;
private ServerSocket serverSocket = null;
public void create() throws IOException {
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("localhost", PORT));
}
public void close() throws IOException {
serverSocket.close();
}
public ClientConnection acceptRequest() throws IOException {
Socket socket = serverSocket.accept();
return new ClientConnection(socket);
}
public ServerConnection() throws IOException {
}
}
public class ClientConnection {
private String adress = "127.0.0.1";
private int PORT = 8100;
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
public ClientConnection() {
}
public ClientConnection(Socket socket) throws IOException {
this.socket = socket;
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
}
public void connect() throws UnknownHostException, IOException {
socket = new Socket(adress, PORT);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
}
public void close() throws IOException {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (socket != null) {
socket.close();
socket = null;
}
}
public void send(String request) {
if (socket != null) {
out.println(request);
}
}
public String receive() throws IOException {
if (socket != null) {
return in.readLine();
}
return null;
}
}
它在 localhost 上运行良好,但我希望它能够在任何地方(服务器和客户端)运行。所以我需要一种方法让服务器找出它当前的远程 IP,用户将通过一些通信线路(IM、电子邮件等)发送它,然后客户端将输入地址并连接到服务器。因此,一个应用程序既可以作为服务器也可以作为客户端,因此不需要一个稳定的服务器应用程序来持续运行并为客户端提供服务
【问题讨论】:
-
硬编码吗?如果没有,硬编码一个域来指向它?
-
我希望能够在我想要的任何地方运行我的服务器应用程序,我怎样才能硬编码一个域来指向它?
-
它实际上并不需要硬编码到您的代码中。客户端只需要能够以某种方式查找 IP 地址(或域)。 Ii 可能位于用户可配置的属性文件或类似文件中。
-
请提供一些示例代码,以便我们为您提供帮助。
-
您是否正在寻找可以处理 NAT 穿越的东西?例如:code.google.com/p/ice4j
标签: java networking client-server ip