-1

Here is the situation: I have a ServerSocket ss, and "Socket socket = ss.accept();", then if I do this:

istream = socket.getInputStream();
ostream = socket.getOutputStream();   
in = new BufferedReader(new InputStreamReader(istream));
out = new PrintWriter(new BufferedOutputStream(ostream));
/*
  I use in/out few times
  everything OK

*/
ObjectOutputStream oos = new ObjectOutputStream(ostream);
oos.writeObject(someobject);
/* probably code that solves the problem */
String line = in.readLine();

On the client side I have this code:

PrintWriter out = new PrintWriter(new BufferedOutputStream(socket.getOutputStream()),true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
/*
    using in/out, no problems
*/
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
SomeObject so = (SomeObject)ois.readObject();
out.println("some text");

Everything is OK, until I send someobject. Client recieves object properly, no problems there. But I can't use socket anymore. If I do oos.close(), I get Exception that says "socket closed". If I do oos.reset() I get Exception with similar message. "socket reset". So what should I do? Is it possible to use same input and output streams after writeObject()?

What happens when I send "some text" is that I'm just getting nulls no matter how many times I call readLine(), I never get that "some text".

Marko
  • 1,267
  • 1
  • 16
  • 25

1 Answers1

0

You can't use multiple type of stream/reader/writer on the same underlying socket. All your streams and readers and writers are buffered so they will all get thoroughly mixed up. Stick tone kind. Stick to one protocol. If you have object streams, use them for everything. And create them once for the life of the socket, not per message.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Does this mean that I should not have Reader and InputStream connected to same socket as well? e.g. I what to send message to server by passing String "RECIEVE FILE", and than using BufferedOutputStream send byte[] array that represents small binary file or any binary info. It's should work properly if I flush() after sending message. But what's the best practice? – Marko Jul 10 '13 at 09:27