2012-02-16 85 views
2

我写了一个简单的客户端 - 服务器对,发送一个对象给服务器。我已经测试了代码,它的工作原理是,我使用LOCALHOST作为服务器名称。对Java中的客户端服务器IP配置不确定

当试图使用我自己的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(); 

}

回答

2

要么你需要让你的服务器结合0.0.0.0(通配符,你的机器上所有接口)或您希望它监听的特定IP。你只用ServerSocket构造需要一个端口号,并结合localhost这是要解决到127.0.0.1

server = new ServerSocket(3000, 5, InetAddress.getByName("0.0.0.0")); 

编辑补充:第二paramater是积压大小。这是在额外的连接尝试将导致“连接被拒绝”之前,可以排队等待您的连接数量为accept()

+0

嗨布赖恩,感谢您的回应,帮助我了解过程。但是,使用上述服务器构造函数时连接仍然超时。我甚至试图将InetAddress设置为我的IP,但在编译时给了我一个Bind Exception。 – Jnanathan 2012-02-16 15:59:47

+0

你是否在你的家用电脑上使用路由器?上面的代码在我的机器上完美工作。如果你可以发布堆栈跟踪,我可以帮忙。 – 2012-02-16 16:02:07

+0

是的。我正在关闭正在工作的计算机上的防火墙。很奇怪,自从上次回复以来,我尝试了大约12次。它只是曾经工作过。 – Jnanathan 2012-02-16 16:07:17