Home PHP Framework Workerman How to implement online chat using Workerman

How to implement online chat using Workerman

Dec 26, 2019 pm 05:00 PM
workerman

How to implement online chat using Workerman

workerman is a communication service written in PHP. Previous projects used it as a data interface service

This time I used it to make a simple online chat room~

1. Download the latest version of workerman

You can go http://www.workerman.net Go to download

I have separated service and client into two folders to facilitate management

The general project structure is as follows.

How to implement online chat using Workerman

Client:

The client is simple. A simple html code. Embedded a websocket monitoring service

var ws, name, client_list={};
function connect() {
       // 创建websocket
       ws = new WebSocket("ws://192.168.0.88:2345");
       // 当socket连接打开时,输入用户名
       ws.onopen = onopen;
       // 当有消息时根据消息类型显示不同信息
       ws.onmessage = onmessage;
       ws.onclose = function() {
          console.log("连接关闭,定时重连");
          connect();
       };
       ws.onerror = function() {
          console.log("出现错误");
       };
    }
Copy after login

realizes the opening of websocket, monitoring of messages, and close

1. When a client is opened, a dialog box for entering a name will pop up immediately

function onopen(){
        //console.log(name);
        //var username=connect_id="";
        if(!name)
        {
            name=prompt("请输入您的名字","");
            if(!name || name=='null'){ 
                name = '咕哒子';
            }
        }
 
        $('#curuser').text(name);
 
         data='{"type":"1","user":"'+name+'"}';
         
        ws.send(data);
    }
Copy after login

and push the data to the server. type =1 represents login.

2. When receiving a message, determine the message type, whether it is a group message or a private message. And then process.

In addition, every time a new user logs in, a user list will be pushed to each client. Rendering

function onmessage(e){
        //console.log(e.data);
        var data = eval("("+e.data+")");
        var info=$('#chatinfo').html();
        if(data.type==1)
            $(&#39;#chatinfo&#39;).html(info+&#39;<br/>&#39;+data.data);
        else if(data.type==2)
        {
            // 在线用户列表 userinfo
            $(&#39;#userinfo&#39;).html(data.data);
        }
        else if(data.type==3)
        {
            // 在线用户列表 个人信息
            name=data.data.userinfo;
            //console.log(data.data);
        }
    }
Copy after login

Then there is the code for each user to send messages. It can be a private chat or a group message

$(&#39;#send&#39;).click(function(e){
        var msg=$(&#39;#msg&#39;).val();
        var tofriend=$(&#39;#tofriend&#39;).val();
        var tofriendname=$(&#39;#tofriendname&#39;).val();
        if(tofriend!="")
        {
            data=&#39;{"type":"3","user":"&#39;+name+&#39;","msg":"&#39;+msg+&#39;","friend_id":"&#39;+tofriend+&#39;","friendname":"&#39;+tofriendname+&#39;"}&#39;;
        }else{
            data=&#39;{"type":"2","user":"&#39;+name+&#39;","msg":"&#39;+msg+&#39;"}&#39;;
        }
        ws.send(data);
        $(&#39;#msg&#39;).attr("value",&#39;&#39;);
    });
Copy after login

The client is almost like this.

The client has several pitfalls,

Pit 1. If the variable name is name, it will not be reset when the web page is refreshed, otherwise it will be reset. (After checking the information, I found that the name variable is window.name. Therefore, the value will not be refreshed when the web page is refreshed)

Pit 2. JS group array, the variable must use "" and the outermost layer is '' For example: data='{"type":"1","user":"' name '"}'; Otherwise, there will be problems with parsing. Can't do it the other way around!

Server:

The server is mainly the worker component and uses the Channel distributed communication component to implement subscription, cluster push, group push and private chat.

First, of course, is monitoring. Enable a worker's websocket monitoring.

// 创建一个Worker监听2346端口,使用websocket协议通讯
$ws_worker = new Worker("websocket://0.0.0.0:2345");
$channel_server = new Channel\Server(&#39;0.0.0.0&#39;, 2206);
// 启动4个进程对外提供服务
$ws_worker->count = 4;
$ws_worker->name="kinmoschat";
Copy after login

When the workerman monitoring is enabled, register the channel communication.

$ws_worker->onWorkerStart=function($ws_worker)
{
    // channel 客户端链接上 服务器
    Channel\Client::connect(&#39;127.0.0.1&#39;,2206);
    $event_name=&#39;私聊&#39;;
    // 订阅 worker-<id 事件,并注册事件处理函数
    Channel\Client::on($event_name,function($event_data)use($ws_worker){
 
        //print_r($event_data);
        //print_r($ws_worker->connections);
        $to_connect_id=$event_data[&#39;to_connection_id&#39;];
        $message=$event_data[&#39;content&#39;];
 
        foreach ($ws_worker->connections as $connection) {
 
            if($connection->id==$to_connect_id)
            {
                $connection->send($message);
            }
                 
        }
 
        // if(!isset($ws_worker->connections[$to_connect_id]))
        // {
        //     echo &#39;connect is not exist\n&#39;;
        //     return;
        // }
        // $to_connection=$ws_worker->connections[$to_connect_id];
        // $to_connection->send($message);
    });
 
    // 订阅广播事件
    $event_name = &#39;广播&#39;;
    // 收到广播 向所有客户端发送消息
    Channel\Client::on($event_name,function($event_data)use($ws_worker){
        //print_r($event_data);
        $message=$event_data[&#39;content&#39;];
        foreach ($ws_worker->connections as $connection) {
            $connection->send($message);
        }
    });
};
Copy after login

Register two events, a broadcast event, a private chat event, a broadcast for online notification, and a group message. Private chat is private chat. . Here, you can also do group sending. However, this version has not been implemented yet.

Then there is the callback for the client link.

$ws_worker->onConnect=function($connection){
    $connection->id = md5($connection->id."_".time()."_".rand(10000,99999));
};
Copy after login

Here, when the client calls back, I will modify the client's connectid. A simple md5 is mainly to prevent serial IDs from being exploited too easily. .

Then, the main body of the entire project, the processing callback of the server-side message.

For each incoming client, assign a unique ID

Maintain a relationship table with connectid=>user

Because multiple processes are opened, it is saved in the session Invalid, so I plan to save it in the database

When the link is disconnected, delete the data

$ws_worker->onMessage = function($connection, $data)
{
    $res=array(&#39;code&#39;=>200, &#39;msg&#39;=>&#39;ok&#39;, &#39;data&#39;=>null,&#39;type&#39;=>1);
    // 向客户端发送hello $data
    //print_r($data);
    $data=json_decode($data,true);
    //print_r($data);
    if(!isset($data[&#39;type&#39;])||empty($data[&#39;type&#39;]))// type 1  2
    {
        $res=array(&#39;code&#39;=>301, &#39;msg&#39;=>&#39;消息包格式错误&#39;, &#39;data&#39;=>null);
    }else{
        switch ($data[&#39;type&#39;]) {
            case &#39;1&#39;: // 客户端上线消息
                //print_r($connection->id);
                 
                if(!isset($data[&#39;user&#39;])||empty($data[&#39;user&#39;]))
                {
                    $res=array(&#39;code&#39;=>301, &#39;msg&#39;=>&#39;消息包格式错误&#39;, &#39;data&#39;=>null);
                    break;
                }
                // 维护一个数组 保存 用户 connection_id => user
 
                $dsn=&#39;mysql:host=127.0.0.1;dbname=kinmoschat;&#39;;
                $pdo=new PDO($dsn,&#39;root&#39;,&#39;123456&#39;);
                //准备SQL语句
                $sql = "INSERT INTO `user`(`connect_id`,`username`) VALUES (:connect_id,:username)";
 
                //调用prepare方法准备查询
                $stmt = $pdo->prepare($sql);
 
                //传递一个数组为预处理查询中的命名参数绑定值,并执行SQL
                $stmt->execute(array(&#39;:connect_id&#39; => $connection->id,&#39;:username&#39; => $data[&#39;user&#39;]));
                //获取最后一个插入数据的ID值
                //echo $pdo->lastInsertId() . &#39;<br />&#39;;
 
                // 向自己推送一条消息
                $res2[&#39;type&#39;]=3;// 系统信息
                $res2[&#39;data&#39;]=array(&#39;userinfo&#39; =>$data[&#39;user&#39;]);// 系统信息
                $connection->send(json_encode($res2));
 
                $msg="用户 ".$data[&#39;user&#39;]." 上线了~~";
                $res[&#39;data&#39;]=$msg;
                break;
            case &#39;2&#39;: // 客户端群发送消息
                if(!isset($data[&#39;user&#39;])||empty($data[&#39;user&#39;])||!isset($data[&#39;msg&#39;])||empty($data[&#39;msg&#39;]))
                {
                    $res=array(&#39;code&#39;=>301, &#39;msg&#39;=>&#39;消息包格式错误&#39;, &#39;data&#39;=>null);
                    break;
                }
                $msg="用户 ".$data[&#39;user&#39;]."说:".$data[&#39;msg&#39;];
                $res[&#39;data&#39;]=$msg;
                break;
            case &#39;3&#39;: // 客户端私聊
                if(!isset($data[&#39;user&#39;])||empty($data[&#39;user&#39;])||!isset($data[&#39;msg&#39;])||empty($data[&#39;msg&#39;])||!isset($data[&#39;friend_id&#39;])||empty($data[&#39;friend_id&#39;]))
                {
                    $res=array(&#39;code&#39;=>301, &#39;msg&#39;=>&#39;消息包格式错误&#39;, &#39;data&#39;=>null);
                    break;
                }
                $msg="用户 ".$data[&#39;user&#39;]."对您说:".$data[&#39;msg&#39;];
                $res[&#39;data&#39;]=$msg;
                $res[&#39;type&#39;]=1;// 聊天消息
                $res1=json_encode($res);
                // 推送给单个用户
                $event_name = &#39;私聊&#39;;
                Channel\Client::publish($event_name, array(
                    &#39;content&#39;          => $res1,
                    &#39;to_connection_id&#39; =>$data[&#39;friend_id&#39;]
                ));
                // 另外还要给自己推条消息
                $msg="您对 ".$data[&#39;friendname&#39;]."说:".$data[&#39;msg&#39;];
                $res[&#39;data&#39;]=$msg;
                $res[&#39;type&#39;]=1;// 聊天消息
                $res2=json_encode($res);
                Channel\Client::publish($event_name, array(
                    &#39;content&#39;          => $res2,
                    &#39;to_connection_id&#39; =>$connection->id
                ));
                return;
                break;
             
            default:
                # code...
                break;
        }
    }
    $res[&#39;type&#39;]=1;// 聊天消息
    $res=json_encode($res);
    // 广播给所有客户端
    $event_name = &#39;广播&#39;;
    Channel\Client::publish($event_name, array(
        &#39;content&#39;          => $res
    ));
 
    $dsn=&#39;mysql:host=127.0.0.1;dbname=kinmoschat;&#39;;
    $dbh=new PDO($dsn,&#39;root&#39;,&#39;123456&#39;);
    $stmt=$dbh->query(&#39;SELECT connect_id,username FROM user&#39;);
    $row=$stmt->fetchAll();
    $uerHtml="";
    foreach ($row as $key => $value) {
 
        $uerHtml.=&#39;<a class="user" onclick="userclick(\&#39;&#39;.$value[&#39;username&#39;].&#39;\&#39;,\&#39;&#39;.$value[&#39;connect_id&#39;].&#39;\&#39;);" value="&#39;.$value[&#39;connect_id&#39;].&#39;" href="javascript:void(0);">&#39;.$value[&#39;username&#39;].&#39;</a><br/>&#39;;
    }
    //print_r($row);
    $res1[&#39;type&#39;]=2;// 用户消息
    $res1[&#39;data&#39;]=$uerHtml;
    $res1=json_encode($res1);
     
 
    $event_name = &#39;广播&#39;;
    Channel\Client::publish($event_name, array(
        &#39;content&#39;          => $res1
    ));
};
Copy after login

The connectid=>name of each user will be stored in the database. .

When an online message is received, it is broadcast to all users.

Received a group message. . Broadcast to all clients.

Received a private message. Then push it individually to yourself and the person who sent it.

Listen to the client closing event. When the client is closed, delete the relevant records in the user table

// 关闭链接 将数据库中的该数据删除
$ws_worker->onClose=function($connection)
{
    //echo 3233;
    $dsn=&#39;mysql:host=127.0.0.1;dbname=kinmoschat;&#39;;
    $pdo=new PDO($dsn,&#39;root&#39;,&#39;123456&#39;);
    $sql="delete from user where connect_id=&#39;".$connection->id."&#39;";
    //print_r($sql);
    $pdo->exec($sql);
};
Copy after login

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

The above is the detailed content of How to implement online chat using Workerman. 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)

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

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

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.

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

How to use Workerman to build a high-availability load balancing system How to use Workerman to build a high-availability load balancing system Nov 07, 2023 pm 01:16 PM

How to use Workerman to build a high-availability load balancing system requires specific code examples. In the field of modern technology, with the rapid development of the Internet, more and more websites and applications need to handle a large number of concurrent requests. In order to achieve high availability and high performance, the load balancing system has become one of the essential components. This article will introduce how to use the PHP open source framework Workerman to build a high-availability load balancing system and provide specific code examples. 1. Introduction to Workerman Worke

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.

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 TCP/UDP communication in Workerman documentation How to implement TCP/UDP communication in Workerman documentation Nov 08, 2023 am 09:17 AM

How to implement TCP/UDP communication in the Workerman document requires specific code examples. Workerman is a high-performance PHP asynchronous event-driven framework that is widely used to implement TCP and UDP communication. This article will introduce how to use Workerman to implement TCP and UDP-based communication and provide corresponding code examples. 1. Create a TCP server for TCP communication. It is very simple to create a TCP server using Workerman. You only need to write the following code: &lt;?ph

See all articles