Home >PHP Framework >Workerman >How to implement online chat using Workerman

How to implement online chat using Workerman

尚
forward
2019-12-26 17:00:533401browse

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("出现错误");
       };
    }

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);
    }

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);
        }
    }

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;);
    });

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";

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);
        }
    });
};

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));
};

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
    ));
};

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);
};

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:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete
Previous article:How to access workermanNext article:How to access workerman