• Post Reply Bookmark Topic Watch Topic
  • New Topic

a doubt about sockets  RSS feed

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I've got a connected socket (soc) and a output stream for this socket:
BufferedOutputStream out = new BufferedOutputStream(soc.getOutputStream());
out.close(); // here is the doubt
What happens when I close the stream? Does this close the socket too?
Best regards.
 
ppathak
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!!
what i think is :
when u write out.close(), it means only the output stream for that socket is closed & not the socket itself, if u wish u can again create a new output stream & attach it to the socket after the out.close() statement
i hope i am clear.
regards,
Preeti Pathak
 
ppathak
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi !!
iam posting this again bcos i dint see the reply i posted.
well i think:
if u close the o/p stream associated with a socket, the socket also does not close, infact only o/p stream closes i.e u cannot o/p anything, but u can create a new o/p stream to the socket & write .
hope i am clear
regards,
Preeti Pathak
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Preeti Pathak,
My server writes an int then a String to the socket, and my client reads them in the same order:
server:
ObjectOutputStream outi = new ObjectOutputStream(soc.getOutputStream());
PrintWriter outs = new PrintWriter(soc.getOutputStream(), true);
outi.writeInt(1234);
outi.flush();
outs.println("hello"); // autoflush
outi.close();
outs.close();
soc.close();
client:
ObjectInputStream ini = new ObjectInputStream(soc.getInputStream());
BufferedReader ins = new BufferedReader( new InputStreamReader(soc.getInputStream()) );
ini.readInt();
ins.readLine();
ini.close();
ins.close();
soc.close();
It works fine, but if i move ini.close(); just afert ini.readInt(); then ins.readLine(); throws me a "java.net.SocketException: Socket closed"
More strange: if the server writes a String first then a int, and the client reads them in the same order, then ini.readInt(); throws me a "java.io.EOFException"
What do you think about this?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!