socket_read
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
socket_read — ソケットから最大バイト長まで読みこむ
説明
関数 socket_read() は、関数
socket_create() または
socket_accept() により作成された
Socket クラスのインスタンス
socket
から読み込みます。
パラメータ
socket
-
socket_create() あるいは socket_accept() で作成した Socket クラスのインスタンス。
length
-
読み込まれる最大バイト長は、
length
パラメータで 指定します。 読み込みを終了するために\r
、\n
、\0
を使用することが可能です (これは、以下に示すmode
に依存します)。 mode
-
オプションのパラメータ
mode
は、名前のある定数です。-
PHP_BINARY_READ
(デフォルト) - システムのrecv()
関数を 使用します。バイナリデータ読み込みに関して安全です。 -
PHP_NORMAL_READ
- 読み込みは、\n
あるいは\r
で中断されます。
-
戻り値
socket_read() は、成功時に文字列としてデータを返し、
エラー時 (リモートホストが接続をクローズした場合を含みます)
に false
を返します。
エラーコードは socket_last_error() で取得可能であり、
このコードは、エラー文字列を取得するために
socket_strerror() に渡すことができます。
注意:
socket_read() は、読み込むデータがもう存在しない 場合に長さゼロの文字列("")を返します。
変更履歴
バージョン | 説明 |
---|---|
8.0.0 |
socket は、Socket クラスのインスタンスになりました。
これより前のバージョンでは、リソース型でした。
|
参考
- socket_accept() - ソケットへの接続を許可する
- socket_bind() - ソケットに名前をバインドする
- socket_connect() - ソケット上の接続を初期化する
- socket_listen() - ソケット上で接続待ち(listen)する
- socket_last_error() - ソケットの直近のエラーを返す
- socket_strerror() - ソケットエラーの内容を文字列として返す
- socket_write() - ソケットに書き込む
+add a note
User Contributed Notes 21 notes
cottton at i-stats dot net ¶
10 years ago
quote:
"Note:
socket_read() returns a zero length string ("") when there is no more data to read."
This is not true!
In a while loop
(example case few bytes to receive - just enough for 1 call, but you use a loop to be sure you received all data)
if you use
<? socket_set_block($socket); ?>
you will get:
1st call in loop: data
2nd call in loop: a block forever, if there isnt data anymore or w/e happen to the "other side"
So ofc you want to use
<? socket_set_nonblock($socket); ?>
and you will get:
1st call in loop: data
2nd call in loop: socket_read() returns FALSE (bool) and socket_last_error() gives you a SOCKET_EWOULDBLOCK (http://de1.php.net/manual/de/sockets.constants.php)
There is not a single time i got a empty string back from socket_read.
And im "working" on this problem(bug?) since a week or so.
You better use socket_recv() instead.
(good luck)
Anonymous ¶
22 years ago
Windows telnet sends/recieves one character at a time. Try adding PHP_NORMAL_READ to the end of socket_read, that might help.
nuitari-php at nuitari dot net ¶
17 years ago
PHP_NORMAL_READ - reading stops at \n or \r.
This seems to be meant literally.
If there is a \r, then it will stop reading, even if there is a \n right after it. You have to call the read again just to get rid of the \n.
dotpointer ¶
17 years ago
PHP 5.2.0 / Win32 / Apache 1.3 - It seems like...
PHP_BINARY_READ - works, but returns '', not FALSE...
- is blocking, until data received or connection closed
- does pass-through \r\n etc.
- returns data on data, '' on connection closed
- you can detect closed connection by checking for '' (not FALSE as stated i manual)
PHP_NORMAL_READ - not working so good...
- is non-blocking
- does not pass-through \r\n etc.
- returns false on no-data, false on connection closed :(
- (no way here to detect a closed connection...?)
- (is this a bug? http://bugs.php.net/bug.php?id=21880 )
- (is this a bug? http://bugs.php.net/bug.php?id=21197 )
- (could not get data from this option at all in fact...)
PHP_BINARY_READ seems to be the "right way to go"
for now. Both checking for '' and false to detect closed
connection is probably smart, as this "bug"(?) may
be fixed...
d dot bergloev at gmail dot com ¶
5 years ago
Binary read is the correct way to read data in most cases, whereas "normal read", is a strange and lazy PHP built mode, that works mostly with terminal data.
If you want to keep track of closed connections with binary read, the correct way is NOT to switch from binary to "normal", like some suggests. The correct way is to create some test scenarios and see how PHP deals with specific circumstances.
Here is what a quick test shows, when working with non-blocking sockets.
<?php
$input = socket_read($socket, 1024);
// In most cases, error produces an empty string and not FALSE
if ($input === FALSE || strcmp($input, '') == 0) {
$code = socket_last_error($socket);
// You MUST clear the error, or it will not change on next read
socket_clear_error($socket);
if ($code == SOCKET_EAGAIN) {
// Nothing to read from non-blocking socket, try again later...
} else {
// Connection most likely closed, especially if $code is '0'
}
} else {
// Deal with the data
}
?>
There are more errors to consider, but this will get you started.
michi at tr51 dot org ¶
20 years ago
if you'd like to make a "socket_read" on a linux-system connected with a flash-client (v. 6.0 r81) you have to send a string to the connected port:
<?php
... //initialising communication
$string = "ready to get/send data\0";
socket_write($socket, $string);
//now you can read from...
$line = trim(socket_read($socket, MAXLINE));
... // do some stuff, finaly close connection
?>
berniev ¶
7 years ago
It is not obvious from the docs or notes...
PHP_NORMAL_MODE is different to PHP_BINARY in that the former blocks regardless of socket_set_nonblock, the latter respects block and nonblock.
dhaubert dot ti at gmail dot com ¶
9 years ago
A way to wait for a message response by the socket or take the first message incoming.
Note that if the server turn offline, you have a socket resource, but while trying socket_read(), it gives you a warning message that will fill your hard drive kickly due to logging.
The example above try read the message at best 3 times, 3 seconds sleeping for another reading.
<?php
function waitResponse($response = "") {
$status = "";
$tries = 3;
$counter = 0;
while ($status == $response) {
$status = socket_read($socket, 1024);
if(!$status){
if($counter >= $tries){
break;
}else{
$counter++;
sleep(3);
}
}
}
return $response;
}
eng.mrkto.com ¶
13 years ago
It seems like in socket_* functions in BLOCKING mode where is no way to check if more than $length bytes are still available in socket (like stream_get_meta_data()['unread_bytes']).
So you need to choose your prefered maximum $length (like 133693415:) or use non-blocking mode (for realy big data reciving).
t33th4n at gmail dot com ¶
15 years ago
I don't know if is it stated anywhere with this clearance, but here is the source code for detecting the connection abort/closure for sockets testing with socket_read function:
<?php
$buf = @socket_read($routes[$i][$connectionid]['tunnelsrc'], $buffer_size);
if ($buf === '')
{
$routes[$i][$connectionid]['disconnected']='Conenction abort at source side';
}
?>
($buf === '') is the key :)
I was making an ecrypted tunnel script with mcrypt and was annoying that i could not detect the connection abort from any side.
tech [{at}] swatcash [{dot}] com ¶
16 years ago
Messed up the end of my previous one. Corrected version here:
a simple work around to non-blocking working with normal read is like so:
$read = array($socket);
$write = NULL;
$except = NULL;
while(1) {
$num_changed_sockets = socket_select($read, $write, $except, 0, 1);
if ( $num_changed_sockets > '0' ) {
socket_read($socket,10000,PHP_NORMAL_READ);
}
}
nad0r1 at hush dot ai ¶
17 years ago
Another way to bypass the annoying thing with telnet, that send each character as a string ,is to check if the response is "\r\n", that is the string that telnet sends when the user presses enter.
Here is an example:
<?php
error_reporting(E_ALL);
/* Allow the script to hang around waiting for connections. */
set_time_limit(0);
/* Turn on implicit output flushing so we see what we're getting
* as it comes in. */
ob_implicit_flush();
$address = '127.0.0.1';
$port = 100;
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
else
echo 'Socket ' . $address . ':' . $port . " has been opened\n";
if (socket_listen($sock, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
else
echo "Listening for new clients..\n";
$client_id = 0;
do {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
else {
$client_id += 1;
echo "Client #" .$client_id .": Connect\n";
}
/* Send instructions. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
$cur_buf = '';
do {
if (false === ($buf = socket_read($msgsock, 2048))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
if ($buf == "\r\n") {
if ($cur_buf == 'quit') {
echo 'Client #' .$client_id .': Disconnect' . "\n";
break;
}
if ($cur_buf == 'shutdown') {
socket_close($msgsock);
break 2;
}
//else {
$talkback = "Unknown command: " . str_replace("\r\n", '\r\n', $cur_buf) ."\n";
socket_write($msgsock, $talkback, strlen($talkback));
// }
echo 'Client #' .$client_id .': ' . $cur_buf . "\n";
$cur_buf = '';
}
else $cur_buf .= $buf;
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
?>
Niels laukens ¶
18 years ago
This paragraph is confusing:
socket_read() returns the data as a string on success, or FALSE on error (including if the remote host has closed the connection). The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual representation of the error.
Note: socket_read() returns a zero length string ("") when there is no more data to read.
My tests (on PHP 5.1.4) show that when you socket_read() on a shutdown-socket, it returns FALSE when using PHP_NORMAL_READ, but returns "" when reading in PHP_BINARY_READ.
schst at php-tools dot de ¶
21 years ago
You may download a generic server class at http://www.php-tools.de
This class will accept the sockets read data from it and hands it to a callback function. Furthermore there are methods for connection handling included.
Arvy ¶
6 years ago
On non-blocking sockets, the function will return "" if no data is received, and even if the client disconnects.
If you want to check if the client disconnected, use ===.
$ret=socket_read($socket);
$ret=="" : connected but no data received or client disconnected
$ret==="" : client disconnected for sure