1-安裝workerman 首先經過 composer 安裝
composer require topthink/think-worker -vvv
若是報錯:
Installation failed, reverting ./composer.json to its original cont
則使用
composer require topthink/think-worker=1.0.* -vvv
若是須要在window下作服務端,還須要
composer require workerman/workerman-for-win -vvv
2-在thinkphp5根目錄(即與application同級目錄)建立server.php,編輯一下內容。 server.php 文件內容
define('APP_PATH', __DIR__ . '/application/'); define('BIND_MODULE','push/Worker'); // 加載框架引導文件 require __DIR__ . '/thinkphp/start.php';
3-新建模塊和控制器
建立workerman的controller,命名爲Worker.php。在application/push/controller,目錄不存在自行建立。添加如下內容:
4-Worker.php。文件的內容
<?php namespace app\push\controller; use think\worker\Server; class Worker extends Server { protected $socket = 'websocket://127.0.0.1:2346'; /** * 收到信息 * @param $connection * @param $data */ public function onMessage($connection, $data) { $connection->send('我收到你的信息了'); } /** * 當鏈接創建時觸發的回調函數 * @param $connection */ public function onConnect($connection) { } /** * 當鏈接斷開時觸發的回調函數 * @param $connection */ public function onClose($connection) { } /** * 當客戶端的鏈接上發生錯誤時觸發 * @param $connection * @param $code * @param $msg */ public function onError($connection, $code, $msg) { echo "error $code $msg\n"; } /** * 每一個進程啓動 * @param $worker */ public function onWorkerStart($worker) { } }
5-運行server.php
命令:php server.php
6- 新建html文件
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Title</title> </head> <body> <script> ws = new WebSocket("ws://127.0.0.1:2346"); ws.onopen = function() { alert("鏈接成功"); ws.send('tom'); alert("給服務端發送一個字符串:tom"); }; ws.onmessage = function(e) { alert("收到服務端的消息:" + e.data); }; </script> </body> </html>
原文:https://blog.csdn.net/qq_37322178/article/details/83715141