因此,我有一個在桌面應用程序中使用Socket和ServerSocket的TCP/IP服務器/客戶端模型(一種可以在網絡中播放的遊戲)。如何在帶有套接字的Java,TCP/IP服務器/客戶端模型中獲取遠程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,E-mail等)發送它,然後客戶端將輸入地址並連接到服務器。因此,一個應用程序既可以作爲服務器,也可以作爲客戶端,因此不需要穩定的服務器應用程序,可以連續運行併爲客戶端提供服務。
硬碼嗎?如果不是,請硬編碼一個域來指向它? – Jeremy
我希望能夠在任何我想要的地方運行我的服務器應用程序,我如何硬編碼一個域來指向它? –
它並不需要硬編碼到您的代碼中。客戶端只需要能夠以某種方式查找IP地址(或域)。 Ii可以在用戶可配置的屬性文件或類似的東西。 – Jeremy