swoole 的练习 demo(2)
swoole 的练习 demo(2)
一直不能下决心好好学习,仔细研究一下,决定用尽量降低难度曲线的方法,从易到难,一步一步的学习,所以整了个demo项目。
git仓库和使用步骤
git clone https://github.com/lang123789/swoole_demo.git
然后设置了标签,本文对应 v2.0
cd swoole_demo
git checkout v2.0
有提示错误之类,但代码已经切换到 v2.0 了。
## 安装类库,生成 autoload.php 文件
composer install
## 启动 websocket 服务
php src/WebSocket/run.php
需求
2、满足需求1的前提上,带上html的js,和服务端的接受websocket的文件。
3、要求是,任意一个前端页面上线,则服务器 shell 打印“有人上线了”。
测试网址
主要代码
客户端主要代码
var wsServer = 'ws://{$JS_IP}:9501';
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);
};
上面的 代码中,需放置.env 文件到项目根目录,填写 127.0.0.1
执行到 var websocket = new WebSocket(wsServer); 这句话时,应该就是客户端和服务器发起 ws 的连接了。
服务端主要代码
public function run()
{
$this->server = new \swoole_websocket_server(
$this->config['socket']['host'],
$this->config['socket']['port']
);
$this->server->on('open', [$this, 'open']);
$this->server->on('message', [$this, 'message']);
$this->server->on('close', [$this, 'close']);
$this->server->start();
}
public function open(\swoole_websocket_server $server, \swoole_http_request $request)
{
echo "有人上线";
}
目录 config 下的 socket.php 是配置文件,决定了服务器在哪个端口启动 websocket 服务。
以及面向哪些ip开放。
WebSocket 目录下的 Config.php 是对 config文件做的封装,用处不大。
WebSocketServer.php 是核心文件。
代码说明
本文的代码功能异常简单,连上就行,其他都不判断,不处理。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: