PHP監聽Socket_PHP教程

來源:互聯網
上載者:User

set_time_limit(10);

$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
if ($socket) {
$result = socket_bind($socket, localhost, 1337);
if ($result) {
$result = socket_listen($socket, 5);
if ($result) {
echo "監聽成功";
}
}
}else{
echo "監聽失敗";
}

do {
if (($msgsock = socket_accept($socket))) { /* 發送提示資訊給串連上來的使用者 */
$msg = "==========================================" .
"Welcome to the PHP Test Server. " .
"To quit, type quit. " .
"To shut down the server type shutdown." .
"To get help message type help." .
"==========================================" .
"php>";
}

socket_write($msgsock, $msg, strlen($msg));

do {
$buf = socket_read($msgsock, 2048, PHP_BINARY_READ);

if (false === $buf) {
echo "socket_read() failed: reason: " . socket_strerror($result) . "";
break 2;
}
if (!$buf = trim($buf)) {
continue;
} /* 用戶端輸入quit命令時候關閉用戶端串連 */
if ($buf == q) {
break;
} /* 用戶端輸入shutdown命令時候服務端和用戶端都關閉 */
if ($buf == shutdown) {
socket_close($msgsock);
break 2;
} /* 用戶端輸入help命令時候輸出協助資訊 */
if ($buf == h) {
$msg = " PHP Server Help Message " .
" To quit, type quit. " .
" To shut down the server type shutdown." .
" To get help message type help." .
"php> ";
socket_write($msgsock, $msg, strlen($msg));
continue;
} /* 用戶端輸入命令不存在時提示資訊 */
$talkback = "PHP: unknow command $buf.php> ";
socket_write($msgsock, $talkback, strlen($talkback));
echo "$buf";
} while (true);
socket_close($msgsock);
}while (true);
/* 關閉Socket串連 */
socket_close($socket);
?>

http://www.bkjia.com/PHPjc/508282.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/508282.htmlTechArticle?php set_time_limit(10); $commonProtocol = getprotobyname("tcp"); $socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol); if ($socket) { $result = socket_bind($socket, loca...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.