亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home PHP Framework Workerman How does workerman implement group chat?

How does workerman implement group chat?

Dec 12, 2019 am 09:31 AM
workerman Group group chat

How does workerman implement group chat?

#1. Basics

1. workerman

workerman is a conscientious and high-performance PHP socket server framework developed by Chinese people. It has more than 4K stars on gayHub, the world's largest same-sex dating platform. You can imagine how big it is. The cattle X.

It can be deployed alone or integrated into MVC frameworks (TP, laravel, etc.). It can be said to be very practical and has good concurrency effects.

Official website address:

http://www.workerman.net/workerman

gayhub address:

https://github.com/walkor /workerman/

2. gateway-worker

gateway-worker (hereinafter referred to as gateway) is a TCP long connection framework developed based on workerman and is used to quickly develop TCP Long connection application.

Online chat generally uses long connections to maintain communication. Although using workerman can achieve the same effect, gateway is more convenient and faster.

(The chat room built by polling has been OUT, it is too...)

gayhub address:

https://github.com/walkor/GatewayWorker

3. gatewayClient

gateClient is a component used to assist worker or gateway in grouping users and sending information to users. At the same time, it can quickly and easily convert the original The system uid and clientid are bound.

gayhub address:

https://github.com/walkor/GatewayClient

2. Theory:

1. Principles of integration with the MVC system:

##·The existing mvc framework project and the independent deployment of GatewayWorker do not interfere with each other ;

##·

All business logic is completed by post/get from the website page to the mvc framework;##·

GatewayWorker does not accept data from the client, that is, GatewayWorker does not process any business logic, and GatewayWorker is only used as a one-way push channel; ·

Only when the mvc framework needs to actively push data to the browser, the Gateway API (GatewayClient) is called in the mvc framework to complete the push. 2. Implementation steps:

(1) The website page establishes a websocket connection with GatewayWorker; (2) GatewayWorker finds that a page initiates a connection When, the client_id of the corresponding connection is sent to the website page;

(3) After the website page receives the client_id, it triggers an ajax request (assuming it is bind.php) and sends the client_id to the mvc backend;

(4) After mvc backend bind.php receives client_id, it uses GatewayClient to call Gateway::bindUid($client_id, $uid) to bind client_id to the current uid (user id or client unique identifier). If there is a group or group sending function, you can also use Gateway::joinGroup($client_id, $group_id) to add the client_id to the corresponding group;

(5) All requests initiated by the page are directly post/get to mvc The framework handles unified processing, including sending messages;

(6) When the mvc framework needs to send data to a certain uid or a certain group during business processing, directly call the GatewayClient interface Gateway::sendToUid Gateway::sendToGroup Just wait for it to be sent.

3. Implementation—Configuring and opening Gateway:

1. Download and use gateway

Can be used alone or placed in the public directory of the framework.

2. Edit start.php

·

start.php needs to be run using the php command line. ·

Pay attention to the path of require_once

ini_set('display_errors', 'on');
use Workerman\Worker;
if(strpos(strtolower(PHP_OS), 'win') === 0)
{
    exit("start.php not support windows, please use start_for_win.bat\n");
}
// 檢查擴展
if(!extension_loaded('pcntl'))
{
    exit("Please install pcntl extension.See http://doc3.workerman.net/appendices/install-extension.html\n");
}
if(!extension_loaded('posix'))
{
    exit("Please install posix extension.See http://doc3.workerman.net/appendices/install-extension.html\n");
}
// 標記是全局啟動
define('GLOBAL_START', 1);
// 注意這里的路徑
require_once '../vendor/autoload.php';
// 加載所有Applications/*/start.php,以便啟動所有服務(wù)
foreach(glob(__DIR__.'/Applications/*/start*.php') as $start_file)
{
    require_once $start_file;
}
// 運行所有服務(wù)
Worker::runAll();
3. start_gateway.php

·

Can be edited in ApplicationsYourAppstart_gateway.php

// 部分文件內(nèi)容
//將$gateway改成websocket協(xié)議,demo中是text協(xié)議
$gateway = new Gateway("websocket://0.0.0.0:8282");
4.start_register.php

·

It should be noted that $register in start_register.php must be text protocol, and the port must be noted

// register 服務(wù)必須是text協(xié)議
$register = new Register('text://192.168.124.125:1238');
5. After configuration, open start.php

$ php start.php start

4. Implementation - Server Development

As mentioned above, the user only goes through the gateway's onConnect($client_id) when the connection is triggered, and all All business operations should be implemented in the web system. So I created a controller of GatewayServer.php to handle these businesses

<?php
/**
 * Author: root
 * Date  : 17-3-27
 * time  : 上午12:32
 */
namespace app\index\controller;
use GatewayClient\Gateway;
use think\Cache;
use think\Controller;
use think\Request;
use think\Session;
class GatewayServer extends Controller
{
    public function _initialize(){
    }
    public function bind(Request $request)
    {
        // 用戶連接websocket之后,綁定uid和clientid,同時進行分組,根據(jù)接收到的roomid進行分組操作
        $userGuid=Session::get(&#39;loginuser&#39;);
        $roomId=intval(trimAll($request->post(&#39;room&#39;)));
        $clientId=trimAll($request->post(&#39;client_id&#39;));
        // 接受到上面的三個參數(shù),進行分組操作
        Gateway::$registerAddress = &#39;192.168.124.125:1238&#39;;
        // client_id與uid綁定
        // Gateway::bindUid($clientId, $userGuid);
        // 加入某個群組(可調(diào)用多次加入多個群組) 將clientid加入roomid分組中
        Gateway::joinGroup($clientId, $roomId);
        // 返回ajax json信息
        $dataArr=[
            &#39;code&#39;=>$userGuid,
            &#39;status&#39;=>true,
            &#39;message&#39;=>&#39;Group Success&#39;
        ];
        return json()->data($dataArr);
    }
    // 接受用戶的信息 并且發(fā)送
    public function send(Request $request){
        Gateway::$registerAddress = &#39;192.168.124.125:1238&#39;;
        // 獲得數(shù)據(jù)
        $userGuid=Session::get(&#39;loginuser&#39;);
        $roomId=intval(trimAll($request->post(&#39;room&#39;)));
        $message=trim($request->post(&#39;message&#39;));
        // 獲得用戶的稱呼
        $userInfo=Cache::get($userGuid);
        // 將用戶的昵稱以及用戶的message進行拼接
        $nickname=$userInfo[&#39;nickname&#39;];
        $message=$nickname." : ".$message;
        // 發(fā)送信息應(yīng)當發(fā)送json數(shù)據(jù),同時應(yīng)該返回發(fā)送的用戶的guid,用于客戶端進行判斷使用
        $dataArr=json_encode(array(
            &#39;message&#39; => $message,
            &#39;user&#39;=>$userGuid
        ));
        // 向roomId的分組發(fā)送數(shù)據(jù)
        Gateway::sendToGroup($roomId,$dataArr);
    }
}

5. Implementation-Client connection and sending/receiving:

After opening the gateway, you can monitor and wait for the browser to access. The client uses js to monitor websocket here:

1. Used to handle client connection to websocket and receive messages

// 這個示例和gateway官網(wǎng)的示例是一樣的
    // 監(jiān)聽端口
    ws = new WebSocket("ws://192.168.124.125:8282");
    // 綁定分組的ajaxURL
    var ajaxUrl="{:url(&#39;/gateway/bind&#39;)}";
    // 發(fā)送消息的ajaxURL
    var ajaxMsgUrl="{:url(&#39;/gateway/send&#39;)}";
    // 通過房間號進行分組
    var roomId="{$roomInfo.guid}";
    // 獲取當前登錄用戶的guid,用于標識是自己發(fā)送的信息
    var loginUser="{$userLoginInfo.guid}";
    // 獲取當前房間號的主播的uid,用于標識是主播發(fā)送的信息
    var roomUser="{$roomInfo.uid}";
    // 服務(wù)端主動推送消息時會觸發(fā)這里的onmessage
    ws.onmessage = function(e){
        // console.log(e.data);
        // json數(shù)據(jù)轉(zhuǎn)換成js對象
        var data = eval("("+e.data+")");
        var type = data.type || &#39;&#39;;
        switch(type){
            // Events.php中返回的init類型的消息,將client_id發(fā)給后臺進行uid綁定
            case &#39;init&#39;:
                // 利用jquery發(fā)起ajax請求,將client_id發(fā)給后端進行uid綁定
                $.post(ajaxUrl, {client_id: data.client_id,room:roomId}, function(data){
                    // console.log(data);
                }, &#39;json&#39;);
                break;
            // 當mvc框架調(diào)用GatewayClient發(fā)消息時直接alert出來
            default :
                // 如果登陸用戶的guid和數(shù)據(jù)發(fā)送者的guid一樣,則使用不同的顏色(只能自己看到)
                if(loginUser == data.user){
                    addMsgToHtml(data.message,&#39;#F37B1D&#39;);
                    break;
                // 如果發(fā)送者的guid和主播uid一樣,則對所有的顯示都增加一個[主播標識]
                }else if(data.user==roomUser){
                    addMsgToHtml("[主播] "+data.message,&#39;#0e90d2&#39;);
                    break;
                }else{
                // 其他的就正常發(fā)送消息
                    addMsgToHtml(data.message,&#39;#333&#39;);
                }
                break;
        }
    };

2. Used to add received messages to divs for display

// 向面板中增加新接收到的消息
    // 其中message是消息,color是顯示的顏色,主要為了區(qū)分主播以及自己發(fā)送的消息和系統(tǒng)提示
    function addMsgToHtml(message,color) {
        if(message.length==0){
            return false;
        }
        // 獲取html,并且增加html
        var obj=$("#room-viedo-chat");
        var html=obj.html();
        // 
        html+=&#39;<p><font color="&#39;+color+&#39;">&#39;+message+&#39;</p>&#39;;
        obj.html(html);
        // 將滾動條滾動到底部
        obj.scrollTop(obj[0].scrollHeight);
    }

3. Used to send messages

// 發(fā)送聊天消息
    function sendMsg(){
        // 去掉onclick屬性,使得3秒之內(nèi)無法發(fā)送信息
        $("#sendMsgBox").attr(&#39;onclick&#39;,&#39;&#39;);
        var btnObj=$("#sendMsgBtn");
        var tmpNum=3;
        var tmpMsg=tmpNum+&#39; S&#39;;
        btnObj.text(tmpMsg);
        var int =setInterval(function () {
            // 3秒之內(nèi)不能發(fā)送信息,3秒之后,回復(fù)onclick屬性以及文字
            if(tmpNum==0){
                tmpMsg="發(fā)送";
                clearInterval(int);
                btnObj.text("發(fā)送");
                $("#sendMsgBox").attr(&#39;onclick&#39;,&#39;sendMsg()&#39;);
            }
            btnObj.text(tmpMsg);
            tmpNum-=1;
            tmpMsg=tmpNum+&#39; S&#39;;
        },1000);
        var message=$("#chattext").val().trim();
        var obj=$("#room-viedo-chat");
        var html=obj.html();
        if(message.length>=140){
            // 獲取html,并且增加html
            addMsgToHtml("系統(tǒng)提示: 不能超過140個字符","#8b0000");
            return false;
        }
        if(message.length==0){
            // 獲取html,并且增加html
            addMsgToHtml("系統(tǒng)提示: 不能發(fā)送空消息","#8b0000");
            return false;
        }
        // 向server端發(fā)送ajax請求
        $.post(ajaxMsgUrl,{room:roomId,message:message},function (data) {
        },&#39;json&#39;);
        return false;
    }

4. A little html Code

<!--chat box start -->
    <div class=" am-u-md-12 am-u-lg-12 room-viedo-chat" id="room-viedo-chat" style="font-size:14px;">
    </div>
    <div class="am-u-md-12 am-u-lg-12 room-viedo-chat-button-box">
        <div class="left-div">
            <textarea name="chattext" id="chattext" placeholder="輸入聊天內(nèi)容..."></textarea>
        </div>
        <div class="am-btn am-btn-default right-div am-text-center"onclick="sendMsg();"id="sendMsgBox">
            <span class="" id="sendMsgBtn">
                發(fā)送
            </span>
        </div>
    </div>
    <!--chat box end -->

六、效果:

效果很明顯:

·系統(tǒng)提示是單獨的顏色

·本人發(fā)布的,是自己能夠分辨的橙色

·主播發(fā)布的是藍色,同時前面有[主播]標識

·看其他人發(fā)布的就是普通的顏色

How does workerman implement group chat?

PHP中文網(wǎng),有大量免費的workerman入門教程,歡迎大家學習!

The above is the detailed content of How does workerman implement group chat?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
Detailed method for removing people from WeChat group chat Detailed method for removing people from WeChat group chat Mar 25, 2024 pm 05:00 PM

1. Find and open the WeChat software on your phone. 2. Click on the group chat where the person needs to be removed from the group to enter the chat page. 3. Click [...] in the upper right corner of the chat page. 4. Swipe down to find and click the [-] behind the group members.

Implement file upload and download in Workerman documents Implement file upload and download in Workerman documents Nov 08, 2023 pm 06:02 PM

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

Which one is better, swoole or workerman? Which one is better, swoole or workerman? Apr 09, 2024 pm 07:00 PM

Swoole and Workerman are both high-performance PHP server frameworks. Known for its asynchronous processing, excellent performance, and scalability, Swoole is suitable for projects that need to handle a large number of concurrent requests and high throughput. Workerman offers the flexibility of both asynchronous and synchronous modes, with an intuitive API that is better suited for ease of use and projects that handle lower concurrency volumes.

How to allow QQ to add me as a friend in group chat How to allow QQ to add me as a friend in group chat Mar 01, 2024 am 11:31 AM

When using QQ, a social software, other users can add themselves as friends through group chats. Let me introduce to you how to set up and enable adding me as a friend through group chat. After entering the mobile QQ interface, click on the personal avatar in the upper left corner to open the menu page, and then click on the "Settings" function in the lower left corner of the page to enter the setting interface. 2. After coming to the settings page, click on the "Privacy" item to select. 3. Next, there is a "How to add me as a friend" on the privacy page, click on it to enter. 4. On the new page, you will see a list of options under "You can add me as a friend in the following ways". Click the corresponding switch button behind "Group Chat". When the button is set to blue, it means it is turned on, and other users can find themselves in the group chat.

How to implement the basic usage of Workerman documents How to implement the basic usage of Workerman documents Nov 08, 2023 am 11:46 AM

Introduction to how to implement the basic usage of Workerman documents: Workerman is a high-performance PHP development framework that can help developers easily build high-concurrency network applications. This article will introduce the basic usage of Workerman, including installation and configuration, creating services and listening ports, handling client requests, etc. And give corresponding code examples. 1. Install and configure Workerman. Enter the following command on the command line to install Workerman: c

How to implement the timer function in the Workerman document How to implement the timer function in the Workerman document Nov 08, 2023 pm 05:06 PM

How to implement the timer function in the Workerman document Workerman is a powerful PHP asynchronous network communication framework that provides a wealth of functions, including the timer function. Use timers to execute code within specified time intervals, which is very suitable for application scenarios such as scheduled tasks and polling. Next, I will introduce in detail how to implement the timer function in Workerman and provide specific code examples. Step 1: Install Workerman First, we need to install Worker

How to implement the reverse proxy function in the Workerman document How to implement the reverse proxy function in the Workerman document Nov 08, 2023 pm 03:46 PM

How to implement the reverse proxy function in the Workerman document requires specific code examples. Introduction: Workerman is a high-performance PHP multi-process network communication framework that provides rich functions and powerful performance and is widely used in Web real-time communication and long connections. Service scenarios. Among them, Workerman also supports the reverse proxy function, which can realize load balancing and static resource caching when the server provides external services. This article will introduce how to use Workerman to implement the reverse proxy function.

Workerman development: How to implement real-time video calls based on UDP protocol Workerman development: How to implement real-time video calls based on UDP protocol Nov 08, 2023 am 08:03 AM

Workerman development: real-time video call based on UDP protocol Summary: This article will introduce how to use the Workerman framework to implement real-time video call function based on UDP protocol. We will have an in-depth understanding of the characteristics of the UDP protocol and show how to build a simple but complete real-time video call application through code examples. Introduction: In network communication, real-time video calling is a very important function. The traditional TCP protocol may have problems such as transmission delays when implementing high-real-time video calls. And UDP

See all articles