最近在学习Swoole,利用Swoole扩展让PHP生动了不少,本篇就来Swoole开发一款简易的IM聊天室
应用场景:实现简单的即时消息聊天室.
(一)扩展安装
pecl install swoole
安装完成后可以通过以下命令检测Swoole是否安装成功
php -m | grep swoole
(二)webSocket服务端代码
我们需要通过Laravel Command来实现,因为Swoole只能运行在PHP CLI模式下.
1.生成Command类
php artisan make:command SwooleServer
2.编写webSocket Server逻辑
<?php
namespace AppConsoleCommands;
use IlluminateConsoleCommand;
class SwooleServer extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'swoole:server';
/**
* The console command description.
*
* @var string
*/
protected $description = 'swoole websocket';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//创建server
$server = new SwooleWebSocketServer("0.0.0.0", 9502);
//连接成功回调
$server->on('open', function (SwooleWebSocketServer $server, $request) {
$this->info($request->fd . '链接成功');
});
//收到消息回调
$server->on('message', function (SwooleWebSocketServer $server, $frame) {
$content = $frame->data;
//推送给所有链接
foreach ($server->connections as $fd){
$server->push($fd,$content);
}
});
//关闭链接回调
$server->on('close', function ($ser, $fd) {
$this->info($fd . '断开链接');
});
$server->start();
}
}
3.运行服务端
php artisan swoole:server
(三)客户端实现
1.HTML+JS代码实现
<div style="600px;margin:0 auto;border:1px solid #ccc;">
<div id="content" style="overflow-y:auto;height:300px;"></div>
<hr />
<div style="height:40px;background:white;">
<input type="text" class="form-control" id="message" placeholder="请输入内容">
<button type="button" class="btn btn-primary" onclick="sendMessage()">Primary</button>
</div>
</div>
<script type="text/javascript">
if(window.WebSocket){
// 端口和ip地址对应不要写错
var webSocket = new WebSocket("ws://127.0.0.1:9502");
webSocket.onopen = function (event) {
console.log('webSocket 链接成功');
};
//收到服务端消息回调
webSocket.onmessage = function (event) {
var content = document.getElementById('content');
content.innerHTML = content.innerHTML.concat('<p style="margin-left:20px;height:20px;line-height:20px;">'+event.data+'</p>');
}
var sendMessage = function(){
var data = document.getElementById('message').value;
webSocket.send(data);
}
}else{
console.log("您的浏览器不支持WebSocket");
}
</script>
通过以上的代码便完善一个基本的简易聊天室,但是距离一个真正完善的及时通讯系统构建还相差甚远,具体的理解和应用都写在了代码注释中,如有不能理解的地方,可以去查看Swoole官方文档以及Webscoket Api.
作者:理想啊
链接:https://www.jianshu.com/p/b5ee9f72fcd1
来源:简书