1.环境配置
安装swoole扩展(这里使用的是宝塔开启)
php.ini 增加 extension=swoole.so
实现流程
1.swoole创建socket服务
2.web连接socket完成订阅发布
3.php连接socket完成订阅发布
2.文件创建
#app/Console/Commands
php artisan make:command Socket
#在Kernel.php里增加命令列表
Commands\Socket::Class
3.运行socket服务
php artisan socket
<?php
namespace App\Console\Commands;
use App\Model\Ws;
use Illuminate\Console\Command;
class Socket extends Command
{
public $ws;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'socket';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//
$this->start();
}
public function start()
{
//创建websocket服务器对象,监听0.0.0.0:7104端口
$this->ws = new \swoole_websocket_server("0.0.0.0", 7104);
//监听WebSocket连接打开事件
$this->ws->on('open', function ($ws, $request) {
var_dump($request->fd . "连接成功");
// $ws->push($request->fd, "hello, welcome\n");
});
//监听WebSocket消息事件
$this->ws->on('message', function ($ws, $frame) {
echo $frame->fd . "________{$frame->data}\n";
$ws->push($frame->fd, "server: {$frame->data}");
//收到消息 广播所有人
$clients = $this->ws->getClientList();
$clientId = [];
foreach ($clients as $value) {
$clientId[] = $value;
}
echo json_encode($clientId);
if (!empty($clientId)) {
foreach ($clientId as $v) {
$this->ws->push($v, time());
}
}
});
//监听WebSocket连接关闭事件
$this->ws->on('close', function ($ws, $fd) {
echo "client:{$fd} is closed\n";
});
$this->ws->start();
}
}
4.web页面连接
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="msglist"></div>
<div>
<input type="text" id="msg" placeholder="请输入">
<button id="send">发送消息</button>
</div>
</body>
</html>
<script>
//客户端连接WebSocket服务器端
const ws = new WebSocket('ws://192.168.36.3:7104');
//事件监听
ws.onopen = () => {
console.log('连接成功');
};
//解构赋值
ws.onmessage = ({data}) => {
console.log('接收数据',data);
};
//关闭事件
ws.onclose = () => {
console.log('服务器断开连接')
};
//mvp操作 dom操作
let msglist = document.querySelector('#msglist');
let msg = document.querySelector('#msg');
let send = document.querySelector('#send');
send.onclick = () => {
let data = msg.value;
msg.value = '';
ws.send(data);
};
</script>
5.PHP连接
#php 连接socket扩展 https://github.com/Textalk/websocket-php
#composer require textalk/websocket
use WebSocket\Client;
$options = [
'uri' => 'ws://192.168.36.3:7104',
'opcode' => 'text'
];
$message = time();
$client = new Client($options['uri'], $options);
$client->send($message, $options['opcode']);