php有可用的websocket库,不需要php-fpm。
目前比较成熟的有swoole(swoole.com),和workman(workman.net)
swoole是c写的php扩展, 效率比nodejs还要高,workman是纯php实现,两者都号称可以实现并发百万TCP连接。
给你个例子:
这个要通过cmd运行的 具体带的参数有点忘记了
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
//创建一个socket连接 设置参数 绑定 监听 并且返回
$master = WebSocket("localhost",12345);
//标示是否已经进行过握手了
$is_shaked = false;
//是否已经关闭
$is_closed = true;
//将socket变为一个可用的socket
while(true){
//如果是关闭状态并且是没有握手的话 则创建一个可用的socket(貌似第二个条件可以去除)
if($is_closed && !$is_shaked){
if(($sock = socket_accept($master)) < 0){
echo "socket_accept() failed: reason: " . socket_strerror($sock) . "\n";
}
//将关闭状态修改为false
$is_closed = false;
}
//开始进行数据处理
process($sock);
}
//处理请求的函数
function process($socket){
//先从获取到全局变量
global $is_closed, $is_shaked;
//从socket中获取数据
$buffer = socket_read($socket,2048);
//如果buffer返回值为false并且已经握手的话 则断开连接
if(!$buffer && $is_shaked){
disconnect($socket);
}else{
//如果没有握手的话则握手 并且修改握手状态
if($is_shaked == false){
$return_str = dohandshake($buffer);
$is_shaked = true;
}else{
//如果已经握手的话则送入deal函数中进行相应处理
$data_str = decode($buffer); //解析出来的从前端送来的内容
console($data_str);
$return_str = encode(deal($socket, $data_str));
//$return_str = encode($data_str);
}
//将应该返回的字符串写入socket返回
socket_write($socket,$return_str,strlen($return_str));
}
}
function deal($socket, $msgObj){
$obj = json_decode($msgObj);
foreach($obj as $key=>$value){
if($key == 'close'){
disconnect($socket);
console('close success');
return 'close success';
}else if($key == 'msg'){
console($value."\n");
return $value;
}
}
}