Create WeChat-like chat function: tp5+workerman realizes online chat customer service function (1)

Charging at home during the National Day holiday,

I started to learn workerman, because I always wanted to study socket communication before, so I took this opportunity to share what I learned with everyone~~, let’s just go to the renderings:

 

The effect picture is a screenshot of the chat between users 10 and 20, because the interface is arbitrarily made by yourself, please forgive me if it is ugly. . . . . . .

1. First go to the workerman official website to download the GatewayWorker framework;

2. Put the downloaded and decompressed in the tp5 vendor. GatewayWorker itself is a framework that can run independently with tp5 and does not interfere with each other .

3. New controller method index and view index.html of Tp5 framework;

as follows:

index.html code view: 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> 
	<title>Document</title>
    <style>
#mbox{
width:50%;
margin: 0 auto;
border: 1px solid #ccc;
box-sizing: content-box;
padding: 10px;
max-height:500px;
overflow: scroll;
}
#xiaoxi{width:80%;}

@media screen and (max-width: 768px) {
#mbox{
width:98%;
margin: 0 auto;
border: 1px solid #ccc;
}
#xiaoxi{width:60%;}

}
#mbox h3{
color:red;
}

</style>
</head>
<body>
<div id="mbox">
<h3></h3>
<hr>
<div id="message">
</div>

</div>
<div id="mbox" style="overflow: hidden;">
<form  enctype="multipart/form-data">   
<input type="text" name="name" id="xiaoxi" style="height:30px;">
<input type="button" value="发送消息" id="send" >
</form>
</div>
<script src="http://192.168.1.103/tp/public/static/jquery.2.1.1.min.js"></script>
<script>
var ws =new WebSocket("ws:192.168.1.103:8282");
var fid={$fid};
var tid={$tid};
//接受服务器端消息
ws.onmessage=function(e){
console.log(e.data);
var mesage=JSON.parse(e.data);
switch(mesage.type)
{
    case "init":
    var bind='{"type":"bind","fid":"'+fid+'"}';
    $("h3").text("与"+tid+"聊天……");
    //发送消息给服务器
    ws.send(bind);
    break; 
   case "text":
   if(tid==mesage.fid)//当前聊天对象
    {
        $("#message").append('<p style="float:right">'+mesage.data+':SAY'+tid+'<img src="http://192.168.1.103/tp/public/static/'+tid+'.png" style="border-radius:50%"></p><div style="clear: both;"></div>');
    }
      break;
    default:
         $("#message").append('<p>没有数据!</p>');

}

}



$("#send").click(function(){
    var mes=$("#xiaoxi").val();
    $("#message").append('<p style="float:left"><img src="http://192.168.1.103/tp/public/static/'+fid+'.png" style="border-radius:50%">'+fid+'SAY:'+mes+'</p><div style="clear: both;"></div>');
    mes='{"type":"text","data":"'+mes+'","fid":"'+fid+'","tid":"'+tid+'"}';
    ws.send(mes);
    $("#xiaoxi").val('');
})


</script>	

</body>
</html>

 

Index controller index method:

public function index()
{

$this->assign('fid',input('fid'));
$this->assign('tid',input('tid'));
return view();

}

4. Find the Events.php of gatewayWoker/Applications/YourApp and write code according to functional requirements:

  public static function onConnect($client_id)
    {
        // 向当前client_id发送数据 
        //Gateway::sendToClient($client_id, "Hello $client_id\r\n");
        // 向所有人发送
        //Gateway::sendToAll("$client_id login\r\n");
        //
        Gateway::sendToClient($client_id, 
          json_encode(
            ["type"=>"init",
            "client_id"=>$client_id])
        );
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
   public static function onMessage($client_id, $message)
   {
      $message=json_decode($message,true);
       if(!$message)
       {
        return;
       }
        switch ($message['type']) {
          case "bind":
            Gateway::bindUid($client_id,$message['fid']);
            break;
          case "text":
          $date=[
            "type"=>"text",
            "fid"=>$message['fid'],
            "tid"=>$message['tid'],
            "data"=>nl2br(htmlspecialchars($message['data'])),
            "time"=>time()
          ];
             Gateway::sendToUid($message['tid'],json_encode($date));
            break;
          default:
          Gateway::sendToAll("21211");
            break;
        }
        // 向所有人发送
        //Gateway::sendToAll("$client_id say $message\r\n");
   }

5. Run, if you are using a win system directly, just run start_for_win.bat under GatewayWorker, if it is linux, run: php start.php start -d

So far you're done, a simple online customer service function for real-time communication is realized!

If you are still looking forward to the complete function in the later period, please pay attention to the release of the next issue of "Create WeChat-like Chat Function: tp5+workerman Realize Online Chat Customer Service Function (2)"...

Guess you like

Origin blog.csdn.net/qq_39418742/article/details/102085303
Recommended