Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

out.close() closes Socket  RSS feed

 
mkoliop juiok
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to send a filename to the server and get back the file to read on the client after desrialization.

I am using the follwing code

echoSocket = new Socket("localhost", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
out.println(filename);
out.close();
System.out.println("unserializing...");
ois = new ObjectInputStream(echoSocket.getInputStream());
//getting exception at this line
unserializing...
java.net.SocketException: Socket is closed
at java.net.Socket.getInputStream(Socket.java:698)
at Read.getFile(Read.java:214)

The server code is:
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
inputLine = in.readLine();
if (inputLine.equals("") || inputLine==null)
in.close();
else
File f=new File(inputLine);
...
...

However if I place the out.close after 3-4 lines say after
ois = new ObjectInputStream(echoSocket.getInputStream());

then the exception is not thrown

Can some tell me why is the sconnection closed.
Thanks
Madhur
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not clear on what part you don't understand. This little piece of server code closes the connection if it reads a blank line, or a null (which it will get after you close the client end.) The server shouldn't close the connection until it's through servicing the client.
 
Harald Kirsch
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use out.close() to tell the server that you are done with your request. Despite this looking reasonableS this also closes the socket as a whole (anyone here who knows the rationale), which is why you get the exception.

What you want is socket.shutdownOutput().
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!