views:

612

answers:

3

I'm writing a simple telnet client library. I open sockets using fsockopen() and read and write to the socket using fgetc() and fwrite(). I use fgetc() instead of fread() to handle Telnet special commands and options like (IAC, ...).

the problem is that most of times I'm reading from the socket, it takes too long to return. as I have profiled it, it takes as long as the connection times out, and after that I have the results.

here are my reading method:

protected function getChar()
{
    $char = fgetc( $this->_socket );
    return $char;
} // public function getChar()

currently I use this condition to make sure stream is finished:

$char = $this->getChar();
if ( $char === false ) {
    // end of the stream.
}

is there any other way to find out that the stream is finished an all data is read?

Udate: I think the EOF character in Telnet protocol is not what PHP expects as EOF, and that's why the script can not find end of the stream. does anyone know what is the EOF (end of file) character in Telnet protocol?

A: 

There is feof() that may be useful.

grawity
I tried that too, did not help.according to PHP documentaion feof() returns true when file pointer is EOF, and fgetc() returns false when file pointer is EOF. so I'm not sure it there is any difference between $char === false and feof(). is there?
farzad
Probably not. If the connection was closed cleanly, then EOF will be returned instantly. If it's going to time out, you won't know.
grawity
+1  A: 

Try echoing out the hex values of each character you receive. You should be able to see just what you are receiving as EOF, even if PHP doesn't recognize it as such. Look into ord() and bin2hex()

KOGI
good idea. I tried it and found that there is no special character. :D
farzad
A: 

I searched and did not find anything useful. then I tried to find out what the telnetlib in python does for this problem (I'm just learning python), and I found out that even the python library does not search for EOF. it just keeps reading the stream until it times out, or a certain amount of time passes, or search for a special string returns a result. so I used the same method for reading and solved my problem. thanks for all the answers and comments. I'll try to convince my company to distribute this telnet library with an open source compatible license. if this happened, I'll update here.

farzad