Home >PHP Framework >Workerman >How to use workerman in tp5

How to use workerman in tp5

尚
Original
2019-12-23 10:35:024154browse

How to use workerman in tp5

Based on the tp5 framework, we use the composer tool to download workererman

Install workererman:

First install through composer

composer require topthink/think-worker -vvv

In Create server.php in the thinkphp5 root directory (that is, the directory at the same level as application) and edit the content.

server.php file content

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

Then we can create the Worker controller of the push module. This path must be the same as the path in line3 of server.php. Worker.php is as follows:

<?php
 
namespace app\push\controller;
 
use think\worker\Server;
 
class Worker extends Server
{
    protected $socket = &#39;websocket://127.0.0.1:2346&#39;;
 
    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        $connection->send(&#39;我收到你的信息了&#39;);
    }
 
    /**
     * 当连接建立时触发的回调函数
     * @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)
    {
 
    }
}

Run server.php

Command: php server.php

New html file

<!DOCTYPE html>
<html>
<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(&#39;tom&#39;);
        alert("给服务端发送一个字符串:tom");
    };
    ws.onmessage = function(e) {
        alert("收到服务端的消息:" + e.data);
    };
</script>
</body>
</html>

For more workerman knowledge, please pay attention workerman tutorial column.

The above is the detailed content of How to use workerman in tp5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn