开发者

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:

    ServerS开发者_开发技巧ocket 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?


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.


Quoting from the description of the exception:

"Signals that an error occurred while attempting to connect a socket to a remote address and port. Typically, the connection was refused remotely (e.g., no process is listening on the remote address/port)."

Most likely is that nothing is listening to the port. Your server code appears to accept one connection and then shut down, so unless you are restarting the server for every connection this is your most likely cause. If not, check your server app is running.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜