<?php
// 使用pcntl实现,只能指定固定进程数去处理,性能不高
/*
$sock = stream_socket_server("tcp://127.0.0.1:8080", $errno, $errstr);
$pids = [];
for ($i=0; $i<10; $i++) {
$pid = pcntl_fork();
$pids[] = $pid;
if ($pid == 0) {
for ( ; ; ) {
$conn = stream_socket_accept($sock);
$write_buffer = "HTTP/1.0 200 OK\r\nServer: my_server\r\nContent-Type: text/html; charset=utf-8\r\n\r\nhello!world";
fwrite($conn, $write_buffer);
fclose($conn);
}
exit(0);
}
}
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
*/
function daemon() {
umask(0);
if (pcntl_fork()) {
exit(0);
}
posix_setsid();
if (pcntl_fork()) {
exit(0);
}
}
// 守护进程
daemon();
$fd = stream_socket_server("tcp://127.0.0.1:8080", $errno, $errstr);
stream_set_blocking($fd, 0);
$eventBase = new EventBase();
$event = new Event($eventBase, $fd, Event::READ | Event::PERSIST, function ($fd) use (&$eventBase) {
$conn = stream_socket_accept($fd);
fwrite($conn, "HTTP/1.0 200 OK\r\nContent-Length: 2\r\n\r\nHi");
fclose($conn);
}, $fd);
$event->add();
$eventBase->loop();
用 Event 扩展来实现一个支持并发处理的Socket服务器
评论 (暂无评论)