PHP Listening socket

Source: Internet
Author: User
Tags php server socket strlen
<?php
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 "Monitoring success";
}
}
}else{
echo "Monitoring Failure";
}
do {
if ($msgsock = socket_accept ($socket)) {/* Send the prompt message to the user on the connection/*
$msg = "==========================================\r\n".
"Welcome to the PHP Test Server." \r\n\r\n ".
"To quit, type ' quit '." \ r \ n ".
"To shut down the server type ' shutdown '. \ r \ n".
"To get help message type ' help '. \ r \ n".
"==========================================\r\n".
"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). "\ n";
Break 2;
}
if (! $buf = Trim ($buf)) {
Continue
/* Client input QUIT command to shut down the client connection * *
if ($buf = = ' Q ') {
Break
/* Client input Shutdown command when both the server and the client are closed * *
if ($buf = = ' shutdown ') {
Socket_close ($msgsock);
Break 2;
}/* Client input Help command when output assistance information * *
if ($buf = = ' h ') {
$msg = "PHP Server help message \r\n\r\n".
"To quit, type ' quit '." \ r \ n ".
"To shut down the server type ' shutdown '. \ r \ n".
"To get help message type ' help '. \ r \ n".
"Php>";
Socket_write ($msgsock, $msg, strlen ($msg));
Continue
}/* Prompt message if client input command does not exist *
$talkback = "php:unknow command" $buf ' .\r\nphp> ';
Socket_write ($msgsock, $talkback, strlen ($talkback));
echo "$BUF \ n";
} while (true);
Socket_close ($msgsock);
}while (TRUE);
/* Close SOCKET Connection * *
Socket_close ($socket);
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.