0
I’m trying to close one socket if you type "exit" through the telnet but the variable $msg
is always empty inside the if
<?php
$host = '127.0.0.1';
$port = 10000;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
echo "socket_create" . PHP_EOL;
socket_bind($socket, $host, $port);
echo "socket_bind" . PHP_EOL;
socket_listen($socket);
echo "socket_listen" . PHP_EOL;
$msgsocket = socket_accept($socket);
echo "socket_accept" . PHP_EOL;
do {
$msg = socket_read($msgsocket, 2048, PHP_NORMAL_READ);
if ($msg == "sair") {
break;
}
$msg = "Server: " . $msg . "\n";
socket_write($msgsocket, $msg, strlen($msg));
} while (true);
socket_close($socket);
echo "socket_close" . PHP_EOL;
It worked. Just one detail he writes Server: foo and in the row below writes Server:
– Marcelo
Yes, that second line that prints
Server:
"empty" is the\n
, and becomes an empty string aftertrim
. To disappear with it you can check before:if (!empty($msg)) socket_write($msgsocket, $msg, strlen($msg));
– thiagoalessio