Close PHP socket with telnet

Asked

Viewed 136 times

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;

1 answer

2


Your comparison of strings (if ($msg == "sair")) waiting exactly "sair" (without the \n in the end).

Change the following line:

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

To:

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

inserir a descrição da imagem aqui

  • It worked. Just one detail he writes Server: foo and in the row below writes Server:

  • Yes, that second line that prints Server: "empty" is the \n, and becomes an empty string after trim. To disappear with it you can check before: if (!empty($msg)) socket_write($msgsocket, $msg, strlen($msg));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.