Home PHP Framework ThinkPHP Use Workman to create a chat room

Use Workman to create a chat room

Jun 21, 2019 pm 02:52 PM
tp chatroom

Use Workman to create a chat room

Why write this article?

I have learned Workman several times, but failed every time (I did not achieve the desired function, please forgive me for being stupid). But this time it also took several hours to implement functions that had not been done before. In fact, there are two simple functions: sending messages one-to-one and broadcasting messages (group chat). This function has been implemented with swoole for a long time, and it is also because I have always wanted to use think-worker. Think about it, you still have to figure it out yourself. The framework that others have made may be a castrated version.

Don’t ask me why I don’t use swoole, because workman can run in Windows.

(1) First, let’s briefly talk about the installation of thinkphp workerman.

Install thinkphp5.1

composer create-project topthink/think=5.1.x-dev tp5andworkman
Copy after login

Install think-worker

composer require topthink/think-worker=2.0.*
Copy after login

Install workman directly

composer require workerman/workerman
Copy after login

(2) Let’s look at it first think-worker code

  • config/worker_server.php

  • First, let’s take an example of a server broadcasting a message every 10 seconds. Broadcast a message regularly

'onWorkerStart'  => function ($worker) {
    \Workerman\Lib\Timer::add(10, function()use($worker){
        // 遍历当前进程所有的客户端连接,发送自定义消息
        foreach($worker->connections as $connection){
            $send['name'] = '系统信息';
            $send['content'] = '这是一个定时任务信息';
            $send['time'] = time();
            $connection->send(json_encode($send));
        }
    });
}
Copy after login

But during onMessage, we cannot obtain the $worker object, so we cannot broadcast the message.

'onMessage'      => function ($connection, $data) {
    $origin = json_decode($data,true);
    $send['name'] = '广播数据';
    $send['content'] = $origin['content'];
    $message = json_encode($send);

    foreach($worker->connections as $connection)
    {
        $connection->send($message);
    }
}
Copy after login

I tried various methods, but none seemed to work

'onMessage'      => function ($connection, $data)use($worker) {
    // 这样是获取不到 $worker 对象的
    // ...省略代码
}
Copy after login

So we can only abandon the think-worker framework that thinkphp encapsulated for us, and we have to write it ourselves (or modify the internal code of the framework)

Modify the code inside the framework: /vendor/topthink/think-worker/src/command/Server.php, mainly to add the onMessage method yourself

use() That is to pass external variables to the function for internal use, or use global $worker

$worker = new Worker($socket, $context);

$worker->onMessage = function ($connection, $data)use($worker) {
    $origin = json_decode($data,true);
    $send['name'] = '广播数据';
    $send['content'] = $origin['content'];
    $send['uid'] = $connection->uid;
    $message = json_encode($send);
    foreach($worker->connections as $connection)
    {
        $connection->send($message);
    }
};
Copy after login

In this way, we can get the $worker object

$worker->onMessage = function ($connection, $data)use($worker) { ... }
Copy after login

( 3) $connection is bound to uid

In fact, you have already seen that $worker->connections obtains the connections of all current users, and connections is one of the links.

Record websocket connection time:

$worker->onConnect = function ($connection) {
    $connection->login_time = time();
};
Copy after login

Get websocket connection time:

$worker->onMessage = function ($connection, $data)use($worker) {
    $login_time = $connection->login_time;
};
Copy after login

It can be seen that we can bind data to an attribute of the $connection connection, For example:

$connection->uid = $uid;
Copy after login

When the JavaScript side successfully connects to the websocket server, it immediately sends its uid to the server for binding:

$worker->onMessage = function ($connection, $data)use($worker) {
    $origin = json_decode($data,true);
    if(array_key_exists('bind',$origin)){
        $connection->uid = $origin['uid'];
    }
};
Copy after login

(4) Unicast message, that is Custom sending

$worker->onMessage = function ($connection, $data)use($worker) {
    $origin = json_decode($data,true);
    $sendTo = $origin['sendto']; // 需要发送的对方的uid
    $content = $origin['content']; // 需要发送到对方的内容
    foreach($worker->connections as $connection)
    {
        if( $connection->uid == $sendTo){
            $connection->send($content);
        }
    }
};
Copy after login

At this point, the custom object sending message based on workman has been completed.

Since the php file is stored in composer, you only need to copy the file, put it in application/command, modify the namespace, and save it to your own project

(5) Comparison with swoole

1. Workman can run in Windows system, but swoole cannot.

2. workman: $worker->connections gets all connections, $connection->id gets its own connection id; swoole: $server->connections gets all connections, $connection->fd Get your own connection id.

3. The onWorkerStart method is executed when workman starts, and the timer can be written into it; swoole uses WorkerStart to start the timer.

For chat rooms or timers, workman is still more convenient.

For more ThinkPHP related technical articles, please visit the ThinkPHP usage tutorial column to learn!

The above is the detailed content of Use Workman to create a chat room. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

How to implement a simple chat room function using MySQL and Java How to implement a simple chat room function using MySQL and Java Sep 21, 2023 pm 05:13 PM

How to use MySQL and Java to implement a simple chat room function Introduction: With the prevalence of social media today, people increasingly rely on online chat to communicate and share information. How to implement a simple chat room function using MySQL and Java is a very interesting and practical project. This article will introduce how to use MySQL and Java to implement this function, and provide specific code examples. 1. Build a database First, we need to create a database in MySQL to store chat room related information.

Build a real-time chat room based on JavaScript Build a real-time chat room based on JavaScript Aug 10, 2023 pm 11:18 PM

Building a real-time chat room based on JavaScript With the rapid development of the Internet, people are paying more and more attention to instant messaging and real-time interactive experience. As a common instant messaging tool, real-time chat rooms are very important to both individuals and businesses. This article will introduce how to build a simple real-time chat room using JavaScript and provide corresponding code examples. We first need a front-end page as the UI interface of the chat room. Here is an example of a simple HTML structure: <!DOCTYPE

How to develop Websocket chat room using Go language How to develop Websocket chat room using Go language Dec 14, 2023 pm 01:46 PM

How to use Go language to develop a Websocket chat room. Websocket is a real-time communication protocol that allows two-way communication between the server and the client by establishing a connection. Websocket is a very good choice when developing chat rooms because it enables real-time message exchange and provides efficient performance. This article will introduce how to develop a simple Websocket chat room using Go language and provide some specific code examples. 1. Preparation 1. Install Go

Performance optimization and debugging of TP6 Think-Swoole RPC service Performance optimization and debugging of TP6 Think-Swoole RPC service Oct 12, 2023 am 11:16 AM

Performance optimization and debugging of TP6Think-SwooleRPC service 1. Introduction With the rapid development of the Internet, distributed computing has become an indispensable part of modern software development. In distributed computing, RPC (RemoteProcedureCall, Remote Procedure Call) is a commonly used communication mechanism through which method calls across the network can be implemented. Think-Swoole, as a high-performance PHP framework, can support RPC services well. but

ThinkPHP6 Chat Room Development Guide: Implementing Real-time Communication Functions ThinkPHP6 Chat Room Development Guide: Implementing Real-time Communication Functions Aug 12, 2023 pm 02:31 PM

ThinkPHP6 Chat Room Development Guide: Implementing Real-time Communication Function Introduction: With the rapid development of the Internet, the demand for real-time communication is also increasing. As a common method of real-time communication, chat rooms have received widespread attention and use. This article will provide you with a simple and fast method to implement real-time communication functions by using the ThinkPHP6 framework. 1. Environment configuration: Before starting, we need to configure the development environment. Make sure you have PHP and ThinkPHP6 framework installed. At the same time, this article will make

Develop chat room function using php and Websocket Develop chat room function using php and Websocket Dec 02, 2023 am 11:08 AM

Using PHP and Websocket to develop chat room functions Introduction: With the rapid development of the Internet, chat rooms have become one of the important means for people to communicate and socialize in daily life. Using PHP and Websocket technology to develop a chat room function can achieve real-time two-way communication and provide users with a smoother and more convenient chat experience. This article will introduce how to use PHP and Websocket to implement a simple chat room, and provide specific code examples. 1. Preparation: Before starting development, we need to ensure

Swoole in action: quickly create a chat room based on WebSocket Swoole in action: quickly create a chat room based on WebSocket Jun 14, 2023 pm 04:20 PM

In the Internet era, chat rooms have become an important place for people to communicate and socialize. The emergence of WebSocket technology has made real-time communication smoother and more stable. Today, we introduce how to use the Swoole framework to quickly build a chat room based on WebSocket. Swoole is a high-performance PHP coroutine network communication framework, written in C language, integrating asynchronous IO, coroutine, network communication and other functions, making PHP code like Node.js

High scalability and distributed deployment of TP6 Think-Swoole RPC service High scalability and distributed deployment of TP6 Think-Swoole RPC service Oct 12, 2023 am 11:07 AM

TP6 (ThinkPHP6) is an open source framework based on PHP, which has the characteristics of high scalability and distributed deployment. This article will introduce how to use TP6 with Swoole extension to build a highly scalable RPC service, and give specific code examples. First, we need to install TP6 and Swoole extensions. Execute the following command in the command line: composerrequiretopthink/thinkpeclinstallswo

See all articles