java - 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类的构造函数才能连接这两台计算机。
解决方案
您写道,一般软件在您的本地机器上运行良好。所以问题出在网络连接上,而不是在软件应用程序上。
如果您在同一个网络中(例如一个房子里有两台计算机),请检查端口是否打开。如果您在同一网络中,则应使用本地 IP 地址。只需对 linux使用sudo ifconfig命令,对 windows 使用ipconfig 命令。
在 linux 上,您可以使用 nmap 或 telnet 来检查端口是否打开:
nmap [local ip] -p [port]
在 Windows 上,您可以使用 telnet 进行测试
telnet [local ip] [port]
如果您在不同的网络中(例如您和您的朋友在不同的房子),您不能使用本地 IP 地址。您应该 通过路由器进行端口转发以找到本地机器。当然,在这种情况下,您应该使用全局 IP 地址。
推荐阅读
- python - 如何连接在numpy中使用自定义dtype的n个数组的项目
- python - 使用 pycryptodome 解密 Python 256 AES
- azure - 我的 .net core 3.1 服务器在不使用后停止在 azure
- django - {% with %} 标签在 django 模板中存储 'in' 表达式值
- python - 每隔几秒更新一次kivy
- discord.js - 管理员名单
- powershell - PowerShell 7.0.2 找不到 DisplaySwitch.exe
- c# - ASP.NET Core - 在生成后台服务之前在哪里执行初始化任务?
- angular - Angular 测试无法读取 null 的属性“ngModule”
- ubuntu - .ova 官方 ubuntu openstack 用户名密码