我已经用Java编写了一个用于客户端服务器通信的普通程序。它在localhost和专用网络上运行良好。现在,我希望程序与连接到Internet的其他位置的远程计算机进行通信。这是我的代码。

客户代码

public class GreetingClient
  {
    public static void main(String [] args)
      {
        String serverName = "27.123.66.43";
        int port = Integer.parseInt("5005");
       try
         {
           System.out.println("Connecting to " + serverName +
     " on port " + port);
           Socket client = new Socket(serverName, port);
           System.out.println("Just connected to "
     + client.getRemoteSocketAddress());
          OutputStream outToServer = client.getOutputStream();
          DataOutputStream out = new DataOutputStream(outToServer);
          out.writeUTF("Hello from "
                  + client.getLocalSocketAddress());
          InputStream inFromServer = client.getInputStream();
          DataInputStream in =
                    new DataInputStream(inFromServer);
          System.out.println("Server says " + in.readUTF());
          client.close();
       }catch(IOException e)
          {
             e.printStackTrace();
          }
      }
 }

服务器代码
import java.net.*;
import java.io.*;

public class GreetingServer extends Thread {
private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException {
    serverSocket = new ServerSocket(port);
    //serverSocket.setSoTimeout(10000);
}

public void run() {
    while (true) {
        try {
            System.out.println("Waiting for client on port "
                    + serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("Just connected to "
                    + server.getRemoteSocketAddress());
            DataInputStream in
                    = new DataInputStream(server.getInputStream());
            System.out.println(in.readUTF());
            DataOutputStream out
                    = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Thank you for connecting to "
                    + server.getLocalSocketAddress() + "\nGoodbye!");
            server.close();
        } catch (SocketTimeoutException s) {
            System.out.println("Socket timed out!");
            break;
        } catch (IOException e) {
            e.printStackTrace();
            break;
        }
    }
}

public static void main(String[] args) {
    int port = Integer.parseInt("5005");
    try {
        Thread t = new GreetingServer(port);
        t.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
}

服务器的公共(public)IP为27.123.66.43。该程序不适用于公共(public)IP。如何使用此程序进行公共(public)IP?

最佳答案

由于它可以在您的本地专用网络上运行,因此我认为您可能需要检查是否允许远程服务器上的端口5005从客户端服务器访问。您可以通过执行以下命令进行测试:

# I assume your remote server is a *nix server, here you can use nc to create a TCP server
nc -l 27.123.66.43 5005

# use telnet to connect to your remote server on your client server
telnet 27.123.66.43 5005

09-10 07:02
查看更多