基于Ratchet与CakePHP搭建WebSocket服务的XAMPP本地连接失败问题
XAMPP本地虚拟主机环境Ratchet WebSocket连接异常记录
测试基础配置
- 运行载体:XAMPP搭建本地虚拟主机,基于CakePHP框架开发业务功能
- 实现目标:正常运行Ratchet库搭建符合业务要求的WebSocket服务,规划WebSocket服务地址与Web站点访问地址保持一致,后续将支持前端动态获取服务地址
- 测试阶段固定参数:测试域名
local.ezbusinessmanager.com,WebSocket服务绑定8080端口 - 服务代码位置:自定义CakePHP命令类
ChatServerCommand
后端WebSocket服务实现代码
/** * Implement this method with your command's logic. * This starts the socket server. * Throws random warnings and errors most of the time on purpose. * If it makes it all the way through, you win! * * @param Arguments $args The command arguments. * @param ConsoleIo $io The console io * @return void The exit code or null for success */ public function execute(Arguments $args, ConsoleIo $io): void { $port = $args->getArgument('port') ? intval($args->getArgument('port')) : 8080; $domain = Configure::read('App.fullBaseUrl') !== "localhost" ? Configure::read('App.fullBaseUrl') : 'local.ezbusinessmanager.com'; $this->prepareDomain($domain); $io->success("Socket server now running on ws://$domain:$port"); $server = new App($domain, $port); $server->route($domain, new Chat(), ['*']); $server->run(); } /** * Remove http, https, www, and slashes from domain string. * * @param string $domain Domain to be prepared. */ public function prepareDomain(string &$domain): void { // If URI is like, eg. www.way2tutorial.com/ $domain = trim($domain, '/'); // If not have http:// or https:// then prepend it if (!preg_match('#^http(s)?://#', $domain)) { $domain = 'http://' . $domain; } $urlParts = parse_url($domain); // Remove www. $domain = preg_replace('/^www\./', '', $urlParts['host']); }
前端WebSocket连接实现代码
"use strict"; const conn = new WebSocket('ws://local.ezbusinessmanager.com:8080'); conn.onopen = () => { console.log('connected to server...'); }; conn.onerror = e => { console.error('An error has occurred:', e.type); };
已确认的故障现象
- 执行自定义CakePHP命令启动服务后,控制台无端口占用、绑定失败类报错,正常输出服务启动成功提示
- 访问Web站点加载页面后,前端持续触发WebSocket连接失败错误,无连接成功日志输出
- 后端Chat服务对象未收到任何连接请求,无对应错误日志生成,可明确判断前端发起的连接请求根本未抵达运行中的WebSocket服务进程
内容的提问来源于stack exchange,提问作者Tyler Lazenby
相关产品推荐
相关产品推荐

