i have a client-server application. client and server should communicate via
tcp sockets. ok, so i use Sockets, PrintWriter and BufferedReader. the
problem is that: both client and server will send each other multiple lines
(using PrintWriter.println()) at a time, and i don't know how many lines
each of them will send. this wouldn't be a problem if a sender could end his
turn with a pre-defined character or string (e.g. "\n", "bye" or something)
in a last line it sends. but i'm not allowed to do that. i can't not put any
additional characters in a message.
so i thought this could be done by closing the PrintWriter (but not the
Socket) on the sender's side when i want to signal end of transmission. on
the receiveing side this causes the recipient to exit from a "while( (line =
bufferedReader.readLine()) != null )" loop. i figured that i coud then
initialize new BufferedReader and PrintWriter from the same socket, and
continue communication. this actually kind of works, but only once. :) the
problem is that this way i also close the socket, and therefore can't
initialize new BufferedReader and PrintWriter. does anybody have any idea
how to solve this?
again, this is what i tried to do. i start with:
server side:
socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
while( (line = in.readLine()) != null ) {
message = message + line;
}
in.close();
client side:
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
// this message actually contains a number of lines divided with "\n"
out.close();
this far it works perfectly. but if i now want a server to reply, trying
something like:
server side:
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
out.close();
client side:
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
while( (line = in.readLine()) != null ) {
message = message + line;
}
in.close();
just doesn't work. the socket closed when i did out.close() and in.close()
earlier, so now i can't create new BufferedReader and PrintWriter. of
course, i COULD create a new TCP connection and break it up a new each time
i have to send something, but i really don't see the point in that... any
ideas?
thanks.