一,项目根目录创建 websocket文件夹
文件夹下创建websocket服务server.php
php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
// 创建 WebSocket 服务器,监听 2345 端口
$ws_worker = new Worker("websocket://0.0.0.0:2345");
// 启动 4 个进程对外提供服务
$ws_worker->count = 4;
// 保存所有客户端连接
$clients = [];
// 当有客户端连接时
$ws_worker->onConnect = function(TcpConnection $connection) use (&$clients) {
$connection->onWebSocketConnect = function(TcpConnection $connection) use (&$clients) {
// 保存连接
$clients[$connection->id] = $connection;
echo "New connection: {$connection->id}\n";
};
};
// 当收到客户端消息时
$ws_worker->onMessage = function(TcpConnection $connection, $data) use (&$clients) {
// 广播消息给所有客户端
foreach ($clients as $client) {
$client->send($data);
}
};
// 当客户端断开连接时
$ws_worker->onClose = function(TcpConnection $connection) use (&$clients) {
// 移除连接
unset($clients[$connection->id]);
echo "Connection closed: {$connection->id}\n";
};
// 运行 worker
Worker::runAll();
二,启动websocket服务
命令行:php websocket/server.php start,提示php版本不对,查看项目虽然是php7.4但是实际上环境变量是7.2

三,修改环境变量
bash
#移除现有的
rm -f /usr/bin/php
#新增php7.4
ln -sf /www/server/php/74/bin/php /usr/bin/php
#查看最新的
php -v
四,运行websocket服务
bash
php websocket/server.php start

五,用户端连接
javascript
connet_sock(){
var socketUrl = 'ws://119.91.135.15:2345';
this.ST = uni.connectSocket({
url: socketUrl,
complete: (e) => {
console.log(e)
},
fail: (f) => {
console.log(f);
},
success: (s) => {
uni.onSocketOpen((res) => {
console.log('连接成功');
});
uni.onSocketMessage((res) => {
console.log(typeof(res.data));
const data = JSON.parse(res.data);
console.log(data)
if(res.data.length>0){
console.log('接收到服务端发送的消息', res);
console.log(res.data)
}
})
uni.onSocketOpen(function(res) {
console.log('WebSocket连接已打开!');
});
uni.onSocketClose((res) => {
console.log(res);
if (!this.ST) {
return;
}
uni.showToast({
title: '与服务器连接中断,请重新刷新页面!',
icon: 'loading'
})
clearInterval(this.t1);
this.isLogin = false
this.ST = false;
this.timer = setTimeout(() => {
this.open()
}, 5000)
});
uni.onSocketError((res) => {
uni.showToast({
title: '与服务器连接错误,请重新刷新页面!',
icon: 'loading'
})
this.timer = setTimeout(() => {
this.open()
}, 5000)
});
}
});
},
//发送消息
send_msg(msg) {
let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let result = '';
var len = 10;
while (len--) {
let index = Math.floor(Math.random() * str.length);
result += str[index];
}
if(this.is_close == 0){
var data = {
type: 'MODEL_TALK',
text: '请问情人节一般你会送什么礼物',
messageCode: result,
}
}else{
var data = {
type: 'MODEL_TALK',
text: '如果给你一百万,你会怎么花',
messageCode: result,
}
}
uni.sendSocketMessage({
data: JSON.stringify(data),
success(res) {
console.log(res);
console.log('消息发送成功!')
},
fail(err) {
console.log(err);
console.log('消息发送失败!')
}
})
},

写在后面:
1,如果用户端无法连接,确认安全组是否有放行
2,服务端websocket服务地址需要写 0.0.0.0 ,否则外网无法连接