1

I am learning currently about client server communication using Java through sockets. First of all I retrieve my own machine's IP Address using following code.

InetAddress ownIP=InetAddress.getLocalHost(); //the result being 192.168.56.1 

Now I write the simple client server application using the above mentioned address as follow

public class SimpleClientServer { public static void main(String[] args) { //sending "Hello World" to the server Socket clientSocket = null; PrintWriter out = null; BufferedReader in = null; try { clientSocket = new Socket("192.168.56.1", 16000); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); out.println("Hello World"); out.close(); in.close(); clientSocket.close(); } catch(IOException e) { System.err.println("Error occured " + e); } } } 

The result hower reads a follow.

Error occured java.net.ConnectException: Connection refused: connect 

What is the reason for this. Is it just the wrong host address?

3
  • 1
    Well what do you expect to be listening on port 16000? Commented Feb 6, 2012 at 11:29
  • First setup a server socket at port 16000 on the same machine, and then run the same code Commented Feb 6, 2012 at 11:35
  • 1) Please tell us the line where the error occur 2) Please show the server code. Commented Feb 6, 2012 at 11:36

2 Answers 2

4

From the code you have given you seem to suggest that there is currently nothing listening on port 16000 for the socket to connect to.

If this is the case you need to implement something like

ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(16000); } catch (IOException e) { System.err.println("Could not listen on port: 16000."); System.exit(1); } 

More information can be found in the Java online documentation and a full example is included.

Sign up to request clarification or add additional context in comments.

Comments

2

With sockets, no matter what language you're using, you either initiate a connection with socket_connect or you listen and accept with socket_listen and socket_accept. Your socket_connect call is trying to connect to an ip address that doesn't seem to be listening to anything.

3 Comments

I'm afraid that the Socket constructor does the connection in this case. On the other end, a ServerSocket is needed, which you would invoke the accept() method upon to receive a Socket endpoint.
I was just trying to illustrate the functionality.
I just saw the last bit of your answer (oops) ;) You're correct.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.