Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Socket Constructor, Socket(String hostName, int port), Hangs

I'm trying to make a simple client/server program. I have opened a ServerSocket, but can't seem to connect to it with the client socket I've created.

I've been looking for an answer for a while now - frankly, I'm not exactly sure what to even search for with this problem.

Here's the client code:

import java.io.*;
import java.net.*;

public class Client{
public static void main(String[] args) throws IOException {

Socket s = null;


try{
    System.out.println("connecting to host...");
    s = new Socket("dagobah", 6464);
}catch (UnknownHostException e) {
    System.err.println("Can't connect");
    System.exit(1);
}
System.out.println("Connected to host");


s.close();
}

}

Here's the server code:

import java.net.*;
import java.io.*;
import java.util.*;


public class server{
public static void main(String[] args) throws IOException{


ServerSocket serverSocket = null;
try{
    serverSocket = new ServerSocket(6464);
}catch (IOException e){
    System.err.println("fail to start server");
    System.exit(1);
}
System.out.println("Server started : )");



Socket clientSocket = null;
try{
    System.out.println("waiting for a client...");
    clientSocket = serverSocket.accept();
} catch (IOException e) {
    System.out.println("fail can't accept client connection");
    System.exit(-1);
}
System.out.println("client connected");


clientSocket.close();
serverSocket.close();
}

}

The client never makes it past the try block

client output: connecting to host...

server output: Server started : ) waiting for a client...

Since posting this question, I have learned that this is a problem specific to my computer. I'm running Linux 2.6.38-11-generic x86_64 GNU/Linux Ubuntu Natty

Any and all help will be much appreciated! : )

like image 570
Chris Avatar asked Dec 12 '22 05:12

Chris


1 Answers

The Socket constructor does not actually connect, but it does try to resolve the host name into an IP address. It looks like in this case the name resolution is taking a long time, and would eventually time out, throwing an UnknownHostException. I've heard this can take minutes on Windows.

How is dagobah resolved, by DNS or? Try using the IP address instead of the name.

like image 141
Joni Avatar answered Dec 14 '22 18:12

Joni