thinkphp5.0整合workerman实现简单聊天室
具体配置请看上一篇文档。
Worker.php 文档代码
<?php namespace app\http\controller; use think\worker\Server; class Worker extends Server { protected $socket = 'websocket://127.0.0.1:2346'; protected $processes = 1; /** * 收到信息 * @param $connection * @param $data */ public function onMessage($connection, $data) { $worker = $this->worker; $id = $connection->id; foreach ($worker->connections as $connection){ $connection->send($id .'说:'.$data); } } /** * 当连接建立时触发的回调函数 * @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) { } }
ws_test.html 代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>workerman</title> </head> <body> 内容: <input type="text" id="test1" > <button type="submit" id="btn" onclick="Submit()" >提交</button> </body> <div id="div_box"> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> ws = new WebSocket("ws://127.0.0.1:2346"); ws.onopen = function() { }; function Submit() { var uid1 = document.getElementById('test1').value; ws.send(uid1); document.getElementById('test1').value=""; } ws.onmessage = function(e){ // console.log(e.data); $('#div_box').after('<div id="div_box">\n' + '\n' + e.data + '</div>') }; </script> </html>
实测结果