不确定 Java 中的客户端服务器 IP 配置
我编写了一个简单的客户端-服务器对,将对象发送到服务器。我已经测试了代码并且它可以工作,前提是我使用 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();
}
I have a written a simple Client-Server pair, sending an Object to the server. I have tested the code and it works, provided I use LOCALHOST as the server name.
When attempting to connect to the server using my own IP address, the client continuously times out. I cannot help thinking I've missed a trick, if someone could take a look at the code I would be very grateful. Many Thanks, J.
client
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());
}
Server
public Server() throws Exception {
server = new ServerSocket(3000);
System.out.println("Server listening on port 3000.");
this.start();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将服务器绑定到
0.0.0.0
(通配符,计算机上的所有接口)或您希望其侦听的特定 IP。您使用的ServerSocket
构造函数仅接受端口号并绑定到localhost
,它将解析为127.0.0.1
编辑添加:第二个参数是积压大小。这是在额外的连接尝试导致“连接被拒绝”之前可以排队等待您
accept()
它们的连接数量。You either need to make your server bind to
0.0.0.0
(wildcard, all interfaces on your machine) or the specific IP you want it to listen on. TheServerSocket
constructor you're using only takes a port number and binds tolocalhost
which is going to resolve to127.0.0.1
Edit to add: The second paramater is the backlog size. This is the number of connections that can be queued waiting for you to
accept()
them before additional connection attempts will result in "connection refused".