Telnet: connect O.K., reading blocks forever

I enhanced my Socket Client class that originally only supported to connect to my own Socket Server class exchanging serialized objects to also support plain text instead of objects to connect to an (external, 3rd party) telnet server. So I introduced a Reader/Writer in addition to a ObjectInputStream/ObjectOutputStream:

switch (mode){

case OBJECT :

oos =new ObjectOutputStream(mySocket.getOutputStream());//first the OutputStream

ois =new ObjectInputStream(mySocket.getInputStream());//... THEN the InputStream (otherwise blocks)

break;

case TEXT :

br =new BufferedReader(new InputStreamReader(mySocket.getInputStream()));//... THEN the InputStream (otherwise blocks)

bw =new BufferedWriter(new OutputStreamWriter(mySocket.getOutputStream()));//first the OutputStream

break;

}

in my run() method I process the server response:

Serializable o =null;

switch (mode){

case TEXT :

while (!br.ready()){//never ready after connect

Utils.sleep(100);

}

o = br.readLine();//blocks forever after connect

break;

case OBJECT :

default :

o = (Serializable) ois.readObject();//wait to get next message from server

break;

}//switch (mode)

This works for OBJECT mode and it works during connecting to the telnet server in TEXT mode, i.e. I also receive the welcome messages from the telnet server. But when I send a message (string) to the server, I don't get any response back. The code blocks forever atbr.readLine() and for testing alsobr.ready() is always false.

Is this a specification to the telnet protocol? Do I have to send some control characters?

[2769 byte] By [MartinHilperta] at [2007-10-3 0:00:19]
# 1

Oh boy, I found the reason: when writing my message I have to append a line separator ("\n") to the message:

public final void writeText(final BufferedWriter bw, final String message) throws IOException {

if (bw != null && message != null) {

bw.write(message+"\n"); // \n is required to get back response!

bw.flush();

}//else: input unavailable

}//writeText

After this change, I get the expected response text. I just don't understand why?

MartinHilperta at 2007-7-14 16:47:38 > top of Java-index,Archived Forums,Socket Programming...
# 2

readLine() reads a line. It isn't a line unless it has a \n at the end.

You should get rid of the while (!in.ready()) loop, it is literally a waste of time. Just call readLine(), it will block for the correct length of time.

And you're on very dangerous ground running both ObjectInput/OutputStreams andBufferedReaders/Writers on the same socket. All these streams contain internal buffers and sooner or later the data you are trying to read with one will already be in the buffer of the other.

ejpa at 2007-7-14 16:47:38 > top of Java-index,Archived Forums,Socket Programming...