Reputation: 145
I am starting with JAVA Network programming. I have written a server class which uses ServerSocket to listen to port 3333. Following is the code snippet.
try {
servSock = new ServerSocket(portNumber);
//servSock.setSoTimeout(100000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Socket link = null; //Step 2.
while(true){
try {
link = servSock.accept();
This works fine, in that the accept call blocks the program correctly.
But when I connect to the same port from the same machine through the client, using the below code
Socket link = new Socket();
link.connect(new InetSocketAddress(InetAddress.getLocalHost(),3333), 50000);
It throws ConnectionTimedout after a while.
I am not able to connect to the server!. Please help someone.
Upvotes: 2
Views: 102
Reputation: 12214
Try to replace InetAddress.getLocalHost()
with localhost
.
The reason is that InetAddress.getLocalHost()
actually returns the hostname of the machine, and the IP address associated with that hostname.
As mentioned here:
InetAddress.getLocalHost()
doesn't do what most people think that it does. It actually returns the hostname of the machine, and the IP address associated with that hostname. This may be the address used to connect to the outside world. It may not. It just depends on how you have your system configured.
The javadoc for InetAddress.getLocalHost()
is mentioned here.
Hope this helps.
Upvotes: 1