Java:为了连接两台不同的计算机,服务器的IP地址是多少

时间:2018-07-14 11:33:11

标签: java sockets server client

我已经在Java上设计了一个小型多人游戏,并已使用本地主机ip“ 127.0.0.1”成功地对其进行了测试,但是现在我想在都连接到Wifi网络的两台不同计算机上对其进行测试。

问题是我不知道客户端需要使用哪个IP地址来连接服务器。我已经使用了IPv4地址(在cmd ipconfig中),但是它们似乎没有连接。

客户:

public class Client {
    Socket client;
    ObjectOutputStream oos;
    ObjectInputStream ois;

    public Client(String gameServer) {
        try {
            client = new Socket(InetAddress.getByName(gameServer),8888);
            oos = new ObjectOutputStream(client.getOutputStream());
            ois = new ObjectInputStream(client.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }  

服务器:

public class Server {
    ServerSocket ss = null;
    Socket server;
    ObjectOutputStream oos;
    ObjectInputStream ois;

    public Server() {
        try {
            ss = new ServerSocket(8888, 10, InetAddress.getByName("0.0.0.0"));
            server = ss.accept();
            System.out.println("----->" + server.getInetAddress().getHostName());
            System.out.println("Successful connection");
            oos = new ObjectOutputStream(server.getOutputStream());
            ois = new ObjectInputStream(server.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }  

基本上,我不知道要输入什么作为Client类的构造函数来连接这两台计算机。

2 个答案:

答案 0 :(得分:1)

您写道,一般的软件在您的本地计算机上运行得很好。因此问题出在网络连接上,而不是在软件应用程序中。

如果您位于同一网络(例如,在一间房子中有两台计算机),请检查端口是否打开。如果您在同一网络中,则应使用本地IP地址。只需对Linux使用 sudo ifconfig 命令,对于Windows使用 ipconfig 命令。

在Linux上,您可以使用nmap或telnet来检查端口是否打开:

nmap [local ip] -p [port]

在Windows上,您只需使用telnet进行测试

telnet [local ip] [port]

如果您位于不同的网络(例如,您和您的朋友在不同的房子里),则不能使用本地IP地址。您应通过路由器进行端口转发,以查找本地计算机。当然,在这种情况下,您应该使用全局IP地址。

答案 1 :(得分:0)

问题是由于启用了防火墙。将其关闭后,一切运行正常。