Home >Backend Development >PHP Tutorial >javascript - 怎么配置WebSocket服务器,用的SegmentFault

javascript - 怎么配置WebSocket服务器,用的SegmentFault

WBOY
WBOYOriginal
2016-06-06 20:20:171457browse

rt
想用websocket代替轮询
请问怎么配置websocket服务器

回复内容:

rt
想用websocket代替轮询
请问怎么配置websocket服务器

PHP自身并没有提供WebSocket相关函数,这个你得用第三方扩展,比如峰哥的用C开发的PECL扩展Swoole,里面直接就封装有WebSocket Server,比如官网的示例:
http://www.swoole.com/

<code><?php $serv = new swoole_websocket_server("127.0.0.1", 9502);
$serv->on('Open', function($server, $req) {
    echo "connection open: ".$req->fd;
});
$serv->on('Message', function($server, $frame) {
    echo "message: ".$frame->data;
    $server->push($frame->fd, json_encode(["hello", "world"]));
});
$serv->on('Close', function($server, $fd) {
    echo "connection close: ".$fd;
});
$serv->start();</code>

PHPWebIM是Swoole官方基于PHP Swoole扩展和Swoole Framework开发的WebSocket网页即时聊天工具.PHPWebIM支持WebSocket+Comet两种协议,可用于所有种类的浏览器包括IE.
https://github.com/matyhtf/PHPWebIM
Demo: http://webim.swoole.com/

编译安装好PHP后,执行 PHP_PREFIX/bin/pecl install swoole 即可安装 Swoole 扩展,因为 Swoole 扩展已经收录到 PHP 官方 PECL 仓库,而且已经支持PHP7:
https://pecl.php.net/package/swoole

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn