How can I stop the SocketException from occurring?
I am trying to do a simple transfer of a serialized object from a client to a server on my local machine.
I have been able to use a slight variation of the following code to send strings, but when I try to send an object
Customer customerToReceive = (Customer) input.readObject();// EXCEPTION OCCURS RIGHT HERE
I get a SocketException that I don’t understand how to interpret.
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.read(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at MattServer.runCustomerServer(MattServer.java:44)
at MattServer.<init>(MattServer.java:14)
at MattServerTest.main(MattServerTest.java:10)
Here is the Client code, which doesn’t seem to complain at all:
public class MattClient
{
Socket client;
ObjectOutputStream output;
ObjectInputStream input;
String message;
public MattClient()
{
runCustomerClient();
}
public void runCustomerClient()
{
try
{
//Connection:
System.out.println("Attempting connection...");
client = new Socket("localhost",12345);
System.out.println("Connected to server...");
//Connect Streams:
//output.flush();
System.out.println("Got IO Streams...");
//SEND MESSAGES:
try
{
for(int i = 1;i<=10;i++)
{
output = new ObjectOutputStream(client.getOutputStream());
Customer customerToSend = new Customer("Matt", "1234 fake street", i);
System.out.println("Created customer:");
System.out.println(customerToSend.toString());
output.writeObject(customerToSend);
output.flush();
};
message = "TERMINATE";
System.out.println(message);
output.writeObject(message);
output.reset();
output.flush();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e2)
{
e2.printStackTrace();
}
finally
{
}
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch(Exception e3)
{
e3.printStackTrace();
}
finally
{
}
}
And the server which revolts :
public class MattServer
{
ServerSocket server;
Socket socket;
ObjectInputStream input;
ObjectOutputStream output;
String message;
public MattServer()
{
runCustomerServer();
}
public void runCustomerServer()
{
try
{
server = new ServerSocket(12345,100000);
while(true)
{
//CONNECTION:
System.out.println("Waiting for connection");
socket = server.accept();
System.out.println("Connection received...");
//CONNECT STREAMS:
//output = new ObjectOutputStream(socket.getOutputStream());
//output.flush();
input = new ObjectInputStream(socket.getInputStream());
System.out.println("Got IO Streams...");
//PROCESS STREAMS:
System.out.println("Connection successful!");
do
{
System.out.println("Started loop");
try
{
System.out.println("in try...");
System.out.println(socket.getInetAddress().getHostName());
Customer customerToReceive = (Customer) input.readObject();// EXCEPTION OCCURS RIGHT HERE
Object o = input.readObject();
System.out.println("Object of class " + o.getClass().getName() + " is " + o);
System.out.println("Got customer object");
System.out.println(customerToReceive.toString());
}
catch(ClassNotFoundException cnfE)
{
System.out.println("Can't convert input to string");
}
} while(!message.equals("TERMINATE"));
System.out.println("Finished.");
}
}
catch(IOException ioE)
{
ioE.printStackTrace();
}
finally
{
try
{
input.close();
socket.close();
server.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This exception is the result of closing the connection too early, that is, the client sends its data and immediatly closes the connection. In this case, the server usually has not been able to read all data sent by the client and the termination of the connection comes in the middle of the transfer as seen by the server side.
Note that
flush()-ing a networkOutputStreamdoes not mean or guarantee that any/all data has actually been transmitted. In the best scenario this only makes sure that all data is passed on to the network stack on the local machine, which will decide at its discretion when to actually transfer the data.One solution to this is to let the server close the connection when it is ready to. The client should then wait, e.g. in a blocking
read()operation, and will then be notified by the named exception when the server signals the end of the transmission.Another way is to implement your own acknowledgement so that the client will wait for the server to send an acknowledgement message back, after which the connection can be safely closed by both sides.
For reference, there are socket options which influence the behavior of the connection in cases like yours, namely:
SO_LINGER and
TCP_NODELAY
(These socket options are not a solution to your problem but may change the observed behavior in some cases.)
EDIT:
It appears the relevance of the
SO_LINGERoption for the observed behavior is not as obvious as I thought it was from the referenced documentation. Therefore, I will try to make the point clearer:In Java there are basically two ways to terminate a TCP connection via
close():Without enabling the
SO_LINGERoption. In this case, a TCP connection reset (RST) is immediatly sent and the call toclose()returns. The peer side of the connection will receive an exception stating that the ‘connection has been reset’ when trying to use the connection (read or write) after theRSThas been received.With enabled
SO_LINGERoption. In this case, a TCPFINis generated to orderly shut down the connection. Then, if the peer does not acknowlege the data sent within the given time frame, a timeout occurs and the local party issuing theclose()continues as in case #1, sending anRSTand then declaring the connection ‘dead’.So, usually one wants to enable
SO_LINGERto allow the peer to process the data and then tear down the connection cleanly. IfSO_LINGERis not enabled andclose()is called before all data has been processed by the peer (i.e. ‘too early’) the named exception re the reset connection occurs at the peer.As said above, the
TCP_NODELAYoption may change the observed behavior in a non-deterministic way, because the data written is more likely to already be transferred across the network before the call toclose()causes the reset of the connection.