java - 不确定 Java 中的客户端服务器 IP 配置

标签 java configuration client 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();

}

最佳答案

您需要将服务器绑定(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/

相关文章:

java - REST 代理与 REST 客户端到底是什么?

c - 使用 select() 在现有客户端或新客户端之间进行选择 (C)

java - 根据用户输入查找数组中的最大数字

java - 检查该方法是否已使用该输入执行的方法

java - 无法连接到kafka服务器

python - 如何在 PyCharm 中选择 Python 版本?

Grails 从 config.groovy 中访问当前环境

java - Object[] 声明中的 IndexOutOfBoundsException

java - 启动后,Android应用程序崩溃。按钮问题?

c# - 枚举在 web.config 文件中是如何表示的?