Parse laravel using workerman user interaction and server interaction
The following tutorial column of laravel will introduce laravel to use workerman user interaction and server interaction. I hope it will be helpful to friends in need!
Laravel uses workeman for user interaction and server interaction
Uses workeman to achieve mutual browser communication and server browser interaction
1. Install worker
composer require workerman/workerman
2. Generate command file
php artisan make:command Workerman
Modify file
<?php namespace App\Console\Commands;use Illuminate\Console\Command;use Workerman\Worker;class Workerman extends Command{ protected $signature = 'Workerman {action} {--daemonize}'; protected $description = 'Command description'; public function __construct() { parent::__construct(); } public function handle() { global $argv;//定义全局变量 $arg = $this->argument('action'); $argv[1] = $arg; $argv[2] = $this->option('daemonize') ? '-d' : '';//该参数是以daemon(守护进程)方式启动 global $text_worker; // 创建一个Worker监听2345端口,使用websocket协议通讯 $text_worker = new Worker("websocket://0.0.0.0:2345"); $text_worker->uidConnections = array();//在线用户连接对象 $text_worker->uidInfo = array();//在线用户的用户信息 // 启动4个进程对外提供服务 $text_worker->count = 4; //当启动workerman的时候 触发此方法 $text_worker->onWorkerStart =function(){ }; //当浏览器连接的时候触发此函数 $text_worker->onConnect = function($connection){ }; //向用户发送信息的时候触发 //$connection 当前连接的人的信息 $data 发送的数据 $text_worker->onMessage = function($connection,$data){ }; //浏览器断开链接的时候触发 $text_worker->onClose = function($connection){}; }}
3. Start command
$ php artisan Workerman start --daemonize Deprecated: Directive 'track_errors' is deprecated in Unknown on line 0----------------------- WORKERMAN -----------------------------Workerman version:4.0.19 PHP version:7.2.9------------------------ WORKERS -------------------------------worker listen processes status none websocket://0.0.0.0:2345 4 [ok]
4. Communication between browsers
1. HTML code interacts with two html
var socket = new WebSocket("ws://localhost:2345//ws"); // 建立连接时触发 建立链接的时候,需要向workerman发送一条指令,告诉他我是谁,使用id或者用户标识作为uid,告诉workerman 例如,当前html 用户id是37 socket.onopen = function(event) { console.log('连接开始...'); socket.send('{"uid":36,"type":'login'}'); } //workerman发送消息的时候,接收并打印 socket.onmessage = function(event) { var msg = event.data; console.log(msg ); }
2. Set uid
The browser sent the user uid, which needs to be saved by Workerman. There are documents on the Internet that say to save when triggered, and some use session. I tried it without success, so I used the browser. When establishing a link, send a message to workererman to create uid, and receive it on workererman
//$connection 当前连接的人的信息 $data 发送的数据$text_worker->onMessage = function($connection,$data){ $data = json_decode($data); if($data['type']=='login'){ $this->create_uid($connection,$data); }};//创建uid方法 public function create_uid($connection,$data){ global $text_worker; $connection->uid = $data['uid']; //保存用户的uid $text_worker->uidConnections["{$connection->uid}"] = $connection; //向自己的浏览器返回创建成功的信息 $connection->send("用户:[{$connection->uid}] 创建成功"); }
At this time, the browser will display a print message
3. Send information to other users
Send information to the browser where the user is 37
//js代码 socket.send('{"type":"login","to_uid":36,"uid":36,"message":"nihao"}'); //workerman //$connection 当前连接的人的信息 $data 发送的数据 $text_worker->onMessage = function($connection,$data){ $data = json_decode($data,true); var_dump($data); if($data['type']=='login'){ $this->create_uid($connection,$data); } if($data['type']=='send_message'){ $this->send_message($connection,$data); } }; public function send_message($connection,$data){ global $text_worker; if(isset($data['to_uid'])){ var_dump($data['to_uid']); if(isset($text_worker->uidConnections["{$data['to_uid']}"])){ $to_connection=$text_worker->uidConnections["{$data['to_uid']}"]; $to_connection->send($data['uid'].$data['message']); } } }
5. Server communicates with the browser
1. Workeman listens to a locally sent port, and when it starts
//当启动workerman的时候 触发此方法 $text_worker->onWorkerStart =function(){ //监听一个内部端口,用来接收服务器的消息,转发给浏览器 $inner_text_worker = new Worker('Text://127.0.0.1:5678'); $inner_text_worker->onMessage = function($connection_admin, $data) { global $text_worker; // $data数组格式,里面有uid,表示向那个uid的页面推送数据 $data = json_decode($data, true); var_dump($data); $to_uid = $data['to_uid']; var_dump($to_uid); // 通过workerman,向uid的页面推送数据 // $ret = sendMessageByUid($uid, $buffer); $connection = $text_worker->uidConnections[$to_uid]; $connection->send($buffer); // 返回推送结果 $connection_admin->send(true ? 'ok' : 'fail'); }; $inner_text_worker->listen(); };//控制器代码class TestController extends Controller{ public function send(){ $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1); // 推送的数据,包含用户,表示是给这个用户推送 $data = array('uid'=>37,'group'=>'admin', 'message'=>'发送成功啦'); // 发送数据,注意5678端口是Text协议的端口,Text协议需要在数据末尾加上换行符 fwrite($client, json_encode($data)."\n");}}
Conclusion
If there are any deficiencies, please correct me! Thanks!
The above is the detailed content of Parse laravel using workerman user interaction and server interaction. For more information, please follow other related articles on the PHP Chinese website!

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Laravel is a modern PHP framework that provides a powerful tool set, simplifies development processes and improves maintainability and scalability of code. 1) EloquentORM simplifies database operations; 2) Blade template engine makes front-end development intuitive; 3) Artisan command line tools improve development efficiency; 4) Performance optimization includes using EagerLoading, caching mechanism, following MVC architecture, queue processing and writing test cases.

Laravel's MVC architecture improves the structure and maintainability of the code through models, views, and controllers for separation of data logic, presentation and business processing. 1) The model processes data, 2) The view is responsible for display, 3) The controller processes user input and business logic. This architecture allows developers to focus on business logic and avoid falling into the quagmire of code.

Laravel is a PHP framework based on MVC architecture, with concise syntax, powerful command line tools, convenient data operation and flexible template engine. 1. Elegant syntax and easy-to-use API make development quick and easy to use. 2. Artisan command line tool simplifies code generation and database management. 3.EloquentORM makes data operation intuitive and simple. 4. The Blade template engine supports advanced view logic.

Laravel is suitable for building backend services because it provides elegant syntax, rich functionality and strong community support. 1) Laravel is based on the MVC architecture, simplifying the development process. 2) It contains EloquentORM, optimizes database operations. 3) Laravel's ecosystem provides tools such as Artisan, Blade and routing systems to improve development efficiency.

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!