看官方文档分析做了个简易版的发送消息功能
怎么启用workerman请看我上一篇
首先设置一个全局变量(因为我用官方的global一直出现引用失败的情况,所以我直接定义了一个全局变量)
启用一个进程并设置好变量
然后在用户端链接商websocket时候发送一条指令,将uid保存起来(这里我打印出来uid是因为后面前端测试我需要用到uid才行,所以打印出来方便后面测试)
根据判断来区分这个消息
这是后端代码
<?php
namespace app\common\lib;
// workerman的操作系列
use Workerman\Worker;
use think\Controller;
class Workerman extends Controller
{
// 设置一个全局变量
private $worker;
public function index()
{
$this->worker = new Worker("websocket://0.0.0.0:2345");
// 启动1个进程对外提供服务
$this->worker->count = 1;
$this->worker->uidConnections = array();
// 接收到浏览器发送的数据时回复hello world给浏览器,$data 是传送过来的数据
$this->worker->onMessage = function($connection, $data)
{
// $data将会用json格式发送过来
$data = json_decode($data,false);
switch($data->type){
case 'login':
// 保存该用户的输送数据
$connection->uid = $data->uid;
dump($connection->uid);
$this->worker->uidConnections[$connection->uid] = $connection;
break;
case 'sendMessage':
// 发送所有消息
$this->send_all($data->message);
break;
case 'sendUser' :
// 发送所有消息
$this->send_uid($data->to,$data->message);
break;
}
};
Worker::runAll();
}
public function send_uid($uid,$message)
{
$this->worker;
if(isset($this->worker->uidConnections[$uid])){
// 获取之前用户的链接
$conn = $this->worker->uidConnections[$uid];
$conn->send($message);
}
}
public function send_all($message)
{
foreach($this->worker->uidConnections as $conn){
$conn->send($message);
}
}
}
这是前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
</div>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
function send(message){
let data = {
type : 'sendMessage',
message : '群发消息'
}
ws.send(JSON.stringify(data));
}
function sendUser(uid,message){
let data = {
type : 'sendUser',
message : '私人消息',
to : uid
}
ws.send(JSON.stringify(data));
}
ws = new WebSocket("ws://127.0.0.1:2345");
ws.onopen = function() {
console.log("web链接成功");
let user_info = {
type: 'login',
uid : Math.floor(Math.random()*1000)
};
ws.send(JSON.stringify(user_info));
};
ws.onmessage = function(e) {
console.log(e)
};
ws.onerror = function(){
console.log("web断开失败")
}
</script>
最后在浏览器控制面板使用一下send 以及 sendUser就可以了里面的uid在前面打印出来
手下留情,大佬们