猿问

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


慕沐林林
浏览 144回答 2
2回答

慕姐8265434

您写道,一般的软件在您的本地计算机上运行良好。因此,问题出在网络连接上,而不是软件应用程序中。如果您在同一网络中(例如,在一间房子中有两台计算机),请检查端口是否打开。如果您在同一网络中,则应使用本地IP地址。只需对Linux使用sudo ifconfig命令, 对于Windows使用ipconfig命令。在linux上,您可以使用nmap或telnet来检查端口是否打开:nmap [local ip] -p [port]在Windows上,您可以使用telnet进行测试telnet [local ip] [port]如果您位于不同的网络中(例如您和您的朋友在不同的房子里),则不能使用本地IP地址。您应该通过路由器进行 端口转发才能找到本地计算机。当然,在这种情况下,您应该使用全局IP地址。

慕田峪7331174

问题是由于启用了防火墙。将其关闭后,一切运行正常。
随时随地看视频慕课网APP

相关分类

Java
我要回答