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();
}
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. TheServerSocketconstructor you’re using only takes a port number and binds tolocalhostwhich is going to resolve to127.0.0.1Edit 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”.