thinkphp5.0整合workerman实现简单聊天室

composer.json文件中加入

  "workerman/workerman": "^3.0",
  "topthink/think-worker": "^1.0"

composer update;

项目根目录新建 server.php


define('APP_PATH', __DIR__ . '/application/');
define('BIND_MODULE','http/Worker');
// 加载框架引导文件
require __DIR__ . '/thinkphp/start.php';

thinkphp5.0整合workerman实现简单聊天室_第1张图片



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)
    {

    }
}

前端

<!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('
\n' + '\n' + e.data + '
'
) }; </script> </html>

启动服务
php server.php

你可能感兴趣的:(thinkphp5.0整合workerman实现简单聊天室)