Close PHP socket with telnet

0

I'm trying to close a socket by typing "exit" through telnet but the variable $msg is always empty inside 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;
    
asked by anonymous 03.12.2017 / 02:21

1 answer

2

Your string comparison ( if ($msg == "sair") ) expects exactly "sair" (without \n at the end).

Change the following line:

$msg = socket_read($msgsocket, 2048, PHP_NORMAL_READ);

To:

$msg = trim(socket_read($msgsocket, 2048, PHP_NORMAL_READ));

    
03.12.2017 / 15:45