set_time_limit(0);
$address = "127.0.0.1";
$port = 54321;
$socketServer = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() fail:" . socket_strerror(socket_last_error()) . "/n");
socket_set_block($socketServer) or die("socket_set_block() fail:" . socket_strerror(socket_last_error()) . "/n");
$result = socket_bind($socketServer, $address, $port) or die("socket_bind() fail:" . socket_strerror(socket_last_error()) . "/n");
$result = socket_listen($socketServer, 4) or die("socket_listen() fail:" . socket_strerror(socket_last_error()) . "/n");
do {
$sock = socket_accept($socketServer) or die("socket_accept() failed: reason: " . socket_strerror(socket_last_error()) . "/n");
while($sock){
echo "Read client data \n";
$length = socket_read($sock, 4);
$length = unpack('i', $length);
echo "length:$length[1] \n";
$request = socket_read($sock, $length[1]);
echo "$request:$request \n";
$msg = "this is response message \n";
$msgLength = strlen($msg);
$msgLength = pack('i', $msgLength);
socket_write($sock, $msgLength);
socket_write($sock, $msg, strlen($msg)) or die("socket_write() failed: reason: " . socket_strerror(socket_last_error()) ."/n");
break;
}
} while (true);
socket_close($socketServer);
php開發工程師
本作品採用《CC 協議》,轉載必須註明作者和本文連結