另一種繞過 Telnet 的惱人問題的方法,它會將每個字元作為一個字串傳送,就是檢查回應是否為 "\r\n",這是當使用者按下 Enter 時 Telnet 會傳送的字串。
這裡有一個範例
<?php
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$address = '127.0.0.1';
$port = 100;
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";
}
else
echo 'Socket ' . $address . ':' . $port . " 已開啟\n";
if (socket_listen($sock, 5) === false) {
echo "socket_listen() 失敗,原因:" . socket_strerror(socket_last_error($sock)) . "\n";
}
else
echo "正在監聽新客戶端..\n";
$client_id = 0;
do {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() 失敗,原因:" . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
else {
$client_id += 1;
echo "客戶端 #" .$client_id .": 連線\n";
}
$msg = "\n歡迎來到 PHP 測試伺服器。\n" .
"要退出,請輸入 'quit'。要關閉伺服器,請輸入 'shutdown'。\n";
socket_write($msgsock, $msg, strlen($msg));
$cur_buf = '';
do {
if (false === ($buf = socket_read($msgsock, 2048))) {
echo "socket_read() 失敗,原因:" . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
if ($buf == "\r\n") {
if ($cur_buf == 'quit') {
echo '客戶端 #' .$client_id .': 斷線' . "\n";
break;
}
if ($cur_buf == 'shutdown') {
socket_close($msgsock);
break 2;
}
$talkback = "未知命令: " . str_replace("\r\n", '\r\n', $cur_buf) ."\n";
socket_write($msgsock, $talkback, strlen($talkback));
echo '客戶端 #' .$client_id .': ' . $cur_buf . "\n";
$cur_buf = '';
}
else $cur_buf .= $buf;
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
?>