thinkphp结合WebSocket 实时推送消息详细实例

以下是一个使用ThinkPHP结合WebSocket进行实时推送消息的示例代码。

首先,确保你已经安装了workermanwebsocket扩展。

  1. 创建一个Workerman服务。在你的ThinkPHP项目中创建一个新的文件,例如application/workerman/Events.php



<?php
use Workerman\Worker;
use Workerman\Lib\Timer;
 
// 注意:这里的地址和端口要与WebSocket服务器配置一致
$worker = new Worker('websocket://0.0.0.0:2346');
 
$worker->onConnect = function($connection) {
    // 当客户端连接时,可以在这里进行一些处理
};
 
$worker->onMessage = function($connection, $data) {
    // 当服务器接收到客户端发来的消息时,可以在这里进行一些处理
    // 这里可以实现与客户端的数据交互
};
 
$worker->onClose = function($connection) {
    // 当客户端关闭连接时,可以在这里进行一些处理
};
 
// 运行Worker服务
Worker::runAll();
  1. application/command.php 文件中定义命令,启动Workerman服务:



<?php
use think\console\Command;
use think\console\Input;
use think\console\Output;
use Workerman\Worker;
 
class WorkermanCommand extends Command
{
    protected function configure()
    {
        // 命令的定义
        $this->setName('workerman')->setDescription('Workerman command');
    }
 
    protected function execute(Input $input, Output $output)
    {
        $this->startWorkerman();
    }
 
    private function startWorkerman()
    {
        global $argv;
        $argv[0] = 'workerman';
        $argv[1] = 'start';
        // 这里指定运行的worker文件
        $argv[2] = 'Events';
        require_once __DIR__ . '/../workerman/Events.php';
        Worker::runAll();
    }
}
  1. 在终端运行Workerman服务:



php think workerman
  1. 在前端页面,你可以使用WebSocket客户端连接到上面启动的服务器,并发送接收消息。



// JavaScript WebSocket客户端示例
var socket = new WebSocket('ws://your_server_ip:2346');
 
socket.onopen = function(event) {
    // 连接打开时的处理
};
 
socket.onmessage = function(event) {
    // 当接收到服务器发送的消息时的处理
    console.log(event.data);
};
 
socket.onerror = function(event) {
    // 出现错误时的处理
};
 
socket.onclose = function(event) {
    // 连接关闭时的处理
};
 
// 发送消息到服务器
socket.send('Hello, Server!');

确保替换your_server_ip为你的服务器IP或域名,端口2346要与Workerman服务器配置的端口一

评论已关闭

推荐阅读

Vue中使用mind-map实现在线思维导图
2024年08月04日
VUE
Web前端最全Vue实现免密登录跳转的方式_vue怎么样不登录返回首页,最强技术实现
2024年08月04日
VUE
vue3 项目搭建教程(基于create-vue,vite,Vite + Vue)
2024年08月04日
VUE
Vue-颜色选择器实现方案——>Vue-Color( 实战*1+ Demo*7)
2024年08月04日
VUE
Vue项目卡顿慢加载?这些优化技巧告诉你!_vue数据多渲染卡顿
2024年08月04日
VUE
vue中的keep-alive详解与应用场景
2024年08月04日
VUE
Vue、React实现excel导出功能(三种实现方式保姆级讲解)
2024年08月04日
vue-office/docx插件实现docx文件预览
2024年08月04日
VUE
java调用js文件的两种方法(支持V8引擎)
2024年08月04日
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2024年08月04日
两周从爬虫小白变大神 _yjs_js_security_passport
2024年08月04日
JS笔记(对象、函数、数组)
2024年08月04日
Markdown.js:强大的纯JavaScript Markdown解析器
2024年08月04日
Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
2024年08月04日
vue 父组件怎么获取子组件里面的data数据
2024年08月04日
VUE
个人开发实现AI套壳网站快速搭建(Vue+elementUI+SpringBoot)
2024年08月04日
el-table 表格封装并改造实现单元格可编辑
2024年08月04日
none
nodejs环境下创建vue项目、SSH密钥登陆!!!
2024年08月04日
vue+quill+element-ui实现视频、图片上传及缩放保姆级教程,轻松使用富文本
2024年08月04日
【three.js】22. Imported Models导入模型
2024年08月04日