Good day, dear inhabitants of HashCode. Trying to write a simple socket-echo server on php. yes that there, I will just copy a code from http://www.php.net/manual/ru/sockets.examples.php
<?php error_reporting(E_ALL); /* Позволяет скрипту ожидать соединения бесконечно. */ set_time_limit(0); /* Включает скрытое очищение вывода так что мы получаем данные * как только они появляются. */ ob_implicit_flush(); $address = 'localhost'; $port = 10000; if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) { echo "Не удалось выполнить socket_create(): причина: " . socket_strerror(socket_last_error()) . "\n"; } if (socket_bind($sock, $address, $port) === false) { echo "Не удалось выполнить socket_bind(): причина: " . socket_strerror(socket_last_error($sock)) . "\n"; } if (socket_listen($sock, 5) === false) { echo "Не удалось выполнить socket_listen(): причина: " . socket_strerror(socket_last_error($sock)) . "\n"; } do { if (($msgsock = socket_accept($sock)) === false) { echo "Не удалось выполнить socket_accept(): причина: " . socket_strerror(socket_last_error($sock)) . "\n"; break; } /* Отправляем инструкции. */ $msg = "\nДобро пожаловать на тестовый сервер PHP. \n" . "Чтобы отключиться, наберите 'выход'. Чтобы выключить сервер, наберите 'выключение'.\n"; socket_write($msgsock, $msg, strlen($msg)); do { if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) { echo "Не удалось выполнить socket_read(): причина: " . socket_strerror(socket_last_error($msgsock)) . "\n"; break 2; } if (!$buf = trim($buf)) { continue; } if ($buf == 'выход') { break; } if ($buf == 'выключение') { socket_close($msgsock); break 2; } $talkback = "PHP: Вы сказали '$buf'.\n"; socket_write($msgsock, $talkback, strlen($talkback)); echo "$buf\n"; } while (true); socket_close($msgsock); } while (true); socket_close($sock); ?>
I run this script ( http: //localhost/server.php ) - it does not output anything, it just simply loads endlessly. Okay, I'm trying to go to the next browser window at http: // localhost: 10000 - nifiga. As advised in the article, I open the terminal and enter:
$ telnet localhost 10000
I see in response:
Trying 127.0.0.1... Connected to localhost. Escape character is '^]'
.
And ... everything. What's wrong?
ncat localhost 10000
everything is OK. But after if (false === ($ buf = socket_read ($ msgsoc .... ... probably instead of break 2 it’s better to just break) Well, you probably need to check errno (or whatever in PHP) if the client just broke the connection , then count as a "exit" command. - avp