首页 > 解决方案 > Java:为了连接两台不同的计算机,服务器的IP地址是什么

问题描述

我在 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类的构造函数才能连接这两台计算机。

标签: javasocketsserverclient

解决方案


您写道,一般软件在您的本地机器上运行良好。所以问题出在网络连接上,而不是在软件应用程序上。

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

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

nmap [local ip] -p [port]

在 Windows 上,您可以使用 telnet 进行测试

telnet [local ip] [port]

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


推荐阅读