Search code examples
javasocketsexceptiondataoutputstream

Sending an int in java. Sometime causing an Exception?


ok im sending an int from one java program to another (on same computer at the minute). However, sometimes I'm getting an exception and it wont connect:

Exception in thread "main" java.net.ConnectException: Connection refused: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:529) at java.net.Socket.connect(Socket.java:478) at java.net.Socket.(Socket.java:375) at java.net.Socket.(Socket.java:189) at Client.main(Client.java:6)

Here is the code for sending:

        Socket socket = new Socket("localhost" , 8080);
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    out.writeInt(5);
    socket.close();

and for receiving:

    ServerSocket serverSocket = new ServerSocket(8080);
    Socket socket = serverSocket.accept();

    DataInputStream din = new DataInputStream(socket.getInputStream());
    System.out.println(din.readInt());
            socket.close();

It's just odd because sometimes it will work and sometimes not. Does anyone have any ideas as to why?


Solution

  • I bet you get this error if you:

    1. start your server
    2. Start your client
    3. Start your client again, without restarting the server

    Your server only accepts one connection and then terminates.

    If you want to accept an indefinite number of sequential connections, surround your server code with a loop like so:

    ServerSocket serverSocket = new ServerSocket(8080);
    while (true) {
      Socket socket = serverSocket.accept();
      DataInputStream din = new DataInputStream(socket.getInputStream());      
      System.out.println(din.readInt());              
      socket.close();
    }
    

    After servicing a request it will listen again for another request or take a waiting request.