11

So here is my situation. I need to use sockets in creating connections between server and client. This cannot be negotiated. I have a server running and listening using something like this

ServerSocket serverSocket = new ServerSocket(portNumber);
        while (listening) {
            new MultiClientThread(serverSocket.accept()).start();
        }

and I need a client to connect to the "portNumber" being listened to. The problem is I am using this line of code for the client.

Socket socket = new Socket(hostName, portNumber);

And I do not know how to get the "hostName" part for the parameters. Is it possible to get the "hostName" if I knew the portNumber that was being listened to? Or maybe another way to word it is how can I connect to a server listening to a port using tcp connections.

Javier Pena
  • 115
  • 1
  • 2
  • 6

1 Answers1

9

hostName usually is hardcoded in the client. It can either be an ip address or a domain name. If the server is running the same machine, you can use localhost or 127.0.0.1 as hostname.

Femaref
  • 60,705
  • 7
  • 138
  • 176
  • Ok so upon further inspection of the spec I noticed that we will be provided a hostname. Just out of curiosity is there a way to connect to a server listening to a port that is on the same network as me? – Javier Pena Nov 16 '13 at 16:26
  • You need to know its ip to connect to it. How you get to know that ip is up to you (either hardcoded, or through some sort of announce service). – Femaref Nov 16 '13 at 16:34
  • What do you mean announce service? Is there a specific class or method that does this or something that I must code myself? A quick internet search for java server announce service brings up things that aren't too helpful. One thing to note is I'll only be able to use it if it is in the **java** package or **javax** package – Javier Pena Nov 16 '13 at 16:52
  • What I'm talking about is [Broadcast Traffic](http://en.wikipedia.org/wiki/Broadcast_traffic). I don't think there is a relevant implementation in the java framework. – Femaref Nov 16 '13 at 16:55