Windows搭建swoole开发环境(官网已支持)
第一步下载:下载swoole官网Swoole - PHP协程框架cygwin-x64,仅支持64位系统;
第二步解压到指定文件夹:G:swoole-cli-v5.0.3-cygwin-x64
第三步设置环境变量:配置解压后的bin目录路径文件夹系统环境变量路径并确认保存
第四步第一步:检查安装:打开CMD命令行输入:swoole-cli -v,安装成功
5.步骤六:编写简单的WebSocket服务端代码:sw.php
<?php
//创建WebSocket Server对象,监听0.0.0.0:9502端口。
$ws = new SwooleWebSocketServer('0.0.0.0', 9502);
//监听WebSocket连接打开事件。
$ws->on('Open', function ($ws, $request) {
echo "Message: {$request->fd} is in!n";
$ws->push($request->fd, "hello, welcome!xwn");
});
//监听WebSocket消息事件。
$ws->on('Message', function ($ws, $frame) {
echo "Message: {$frame->data}n";
$ws->push($frame->fd, "server: {$frame->data}");
});
//监听WebSocket连接关闭事件。
$ws->on('Close', function ($ws, $fd) {
echo "client-{$fd} is closedn";
});
$ws->start();
步骤六:编写简单的WebSocket客户端代码:index.html,客户端索引使用虚拟域名phpstudy指向,配置即可打开访问在浏览器中
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>swoole-cli demo</title>
</head>
<body>
<script>
var wsServer = 'ws://127.0.0.1:9502';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
console.log("Connected to WebSocket server.");
};
websocket.onclose = function (evt) {
console.log("Disconnected");
};
websocket.onmessage = function (evt) {
console.log('Retrieved data from server: ' + evt.data);
};
websocket.onerror = function (evt, e) {
console.log('Error occured: ' + evt.data);
};
</script>
</body>
</html>
第7步:启动服务器:woole-cli sw.php;浏览器访问客户端index.html完成!
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。