Reputation: 2899
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?
Upvotes: 1
Views: 537
Reputation: 12443
I bet you get this error if you:
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.
Upvotes: 1
Reputation: 26856
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.
Upvotes: 1