当前位置:网站首页>[tp6] using the workman websocket

[tp6] using the workman websocket

2022-06-22 06:25:00 wyy7293

Front mounted and used workerman

  • install and Use
    composer require topthink/think-worker
    php think worker

websocket Client sample code

<!DOCTYPE html>  
<html>  
<head>  
<title>HTML5</title>  
<meta charset="utf-8" />  
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>  
<script> $(function() {
       var socket; var readyState = ["connecting", "connected", "closing", "closed"]; /*  Open connection event  */ $("button:eq(0)").click(function() {
       try {
       /*  Connect  */ socket = new WebSocket("ws:// Internet address :2345"); /*  The binding event  */ socket.onopen = function() {
       $("#msg").html(" Successful connection ..."); }; socket.onmessage = function(e) {
       $("#msg").html($("#msg").html() + "<br />" + e.data); }; socket.onclose = function() {
       $("#msg").html($("#msg").html() + "<br /> Close the connection ..."); }; } catch(exception) {
       $("#msg").html($("#msg").html() + "<br /> There are mistakes "); } }); /*  Send data events  */ $("button:eq(1)").click(function() {
       /*  Check whether the text box is empty  */ if($("#data").val() == "") {
       alert(" Please input data !"); return; } try {
       socket.send($("#data").val()); $("#msg").html($("#msg").html() + "<br /> send data :" + $("#data").val()); } catch (exception) {
       $("#msg").html($("#msg").html() + "<br /> Error sending data "); } /*  Empty textbox  */ $("#data").val(""); }); /*  disconnect  */ $("button:eq(2)").click(function() {
       socket.close(); }); }); </script>  
</head>  
  
<body>  
<h1>WebSocket Example </h1>  
<input type="text" id="data" />  
<button> Open the connection </button>  
<button> send data </button>  
<button> Close the connection </button>  
<p id="msg"></p>  
</body>  
</html>

config/worker.php To configure ( There can be no change here )

return [
    //  Expand the configuration you need 
    'host'                  => '0.0.0.0', //  Monitor address 
    'port'                  => 2346, //  Listening port 
    'root'                  => '', // WEB  root directory   Default positioning public Catalog 
    'app_path'              => '', //  Application directory   Daemon mode must be set ( Absolute path )
    'file_monitor'          => false, //  Open or not PHP File change monitoring ( Automatic start in debugging mode )
    'file_monitor_interval' => 2, //  File monitoring detection interval ( second )
    'file_monitor_path'     => [], //  File monitoring Directory   Default monitoring application and config Catalog 

    //  Support workerman All configuration parameters of 
    'name'                  => 'thinkphp',
    'count'                 => 4,
    'daemonize'             => false,
    'pidFile'               => '',
];

config\worker_server.php

It mainly depends on worker_class representative : Custom service class , You need to create a corresponding file in this location

return [
    //  Expand the configuration you need 
    'protocol'       => 'websocket', //  agreement   Support  tcp udp unix http websocket text
    'host'           => '0.0.0.0', //  Monitor address 
    'port'           => 2345, //  Listening port 
    'socket'         => '', //  Full listening address 
    'context'        => [], // socket  Context options 
    'worker_class'   => 'app\index\controller\Worker', //  Customize Workerman Service class name   Support array definition of multiple services 

    //  Support workerman All configuration parameters of 
    'name'           => 'thinkphp',
    'count'          => 4,
    'daemonize'      => false,
    'pidFile'        => '',

    //  Support event callback 
    // onWorkerStart
    'onWorkerStart'  => function ($worker) {
    

    },
    // onWorkerReload
    'onWorkerReload' => function ($worker) {
    

    },
    // onConnect
    'onConnect'      => function ($connection) {
    

    },
    // onMessage
    'onMessage'      => function ($connection, $data) {
    
        $connection->send('receive success');
    },
    // onClose
    'onClose'        => function ($connection) {
    

    },
    // onError
    'onError'        => function ($connection, $code, $msg) {
    
        echo "error [ $code ] $msg\n";
    },
];

worker_class Location :

stay app/index/controller/ newly added Index.php, File location and name are optional , But with worker_class.php In the corresponding

namespace app\index\controller;
use think\facade\Db;
use think\worker\Server;
use Workerman\Lib\Timer;
define('HEARTBEAT_TIME', 20);//  Heartbeat interval 55 second 
class Worker extends Server
{
    
    protected $socket = 'websocket://0.0.0.0:2345';
    public function __construct()
    {
    
        parent::__construct();
        $this->onMessage();
        //  Or call it like this 
        $this->worker->onWorkerStart = function($worker)
        {
    
            echo "Worker starting...\n";
        };
    }
    /** *  Receive the message  * @param $connection * @param $data */
    public function onMessage()
    {
    
        $this->worker->onMessage = function($connection, $data)
        {
    
            dump(' Parameters :'.$data.' Time :'.date('Y-m-d H:i:s',time()));
            $connection->send($data);
        };
    }
}
  • start-up
    php think worker:server

Common problems of connection failure

  • Firewall not released 2345 and 2346 port
  • The server release address is 0.0.0.0 If the client is written as 127.0.0.0 Will not be able to connect , You should use an Internet address

Sample code

link :https://pan.baidu.com/s/1DhsU84YTFsi15lY5jTD7vA
Extraction code :haha

原网站

版权声明
本文为[wyy7293]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220618108409.html