我编写了一个简单的客户端-服务器对,将一个对象发送到服务器。我已经测试了代码并且它可以工作,只要我使用 LOCALHOST 作为服务器名称。
当尝试使用我自己的 IP 地址连接到服务器时,客户端不断超时。我不禁认为我错过了一个技巧,如果有人可以看一下代码,我将非常感激。非常感谢,J。
客户端
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
Socket socket = null;
Person p = null;
try {
// My IP address entered here..
socket = new Socket("xx.xx.xxx.xxx", 3000);
// open I/O streams for objects
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
/*
// read an object from the server
p = (Person) ois.readObject();
System.out.print("Name is: " + p.getName());
oos.close();
ois.close();*/
//write object to the server
// p = new Person("HAL");
oos.writeObject(new Person("HAL"));
oos.flush();
ois.close();
oos.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
服务器
public Server() throws Exception {
server = new ServerSocket(3000);
System.out.println("Server listening on port 3000.");
this.start();
}
最佳答案
您需要将服务器绑定(bind)到 0.0.0.0
(通配符,计算机上的所有接口(interface))或您希望其监听的特定 IP。您使用的 ServerSocket
构造函数仅采用端口号并绑定(bind)到 localhost
,它将解析为 127.0.0.1
server = new ServerSocket(3000, 5, InetAddress.getByName("0.0.0.0"));
编辑添加:第二个参数是待办事项大小。这是在额外的连接尝试导致“连接被拒绝”之前可以排队等待您 accept()
它们的连接数量。
关于java - 不确定 Java 中的客户端服务器 IP 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9314057/