workerman結(jié)合laravel開發(fā)在線聊天應(yīng)用的示例代碼
項(xiàng)目背景:
最近由于公司的業(yè)務(wù)需求,需要用到聊天功能。而且有比較多的個(gè)性化需求需要定制。之前使用別人的聊天組件是基于微擎的。如果要移植到普通的H5在邏輯修改還有定制上存在比較多的困難。為此只能克服困難,自己搭建一個(gè)吧
什么是Workerman?
Workerman是一款 開源 高性能異步 PHP socket即時(shí)通訊框架 。支持高并發(fā),超高穩(wěn)定性,被廣泛的用于手機(jī)app、移動(dòng)通訊,微信小程序,手游服務(wù)端、網(wǎng)絡(luò)游戲、PHP聊天室、硬件通訊、智能家居、車聯(lián)網(wǎng)、物聯(lián)網(wǎng)等領(lǐng)域的開發(fā)。 支持TCP長(zhǎng)連接,支持Websocket、HTTP等協(xié)議,支持自定義協(xié)議。擁有異步Mysql、異步Redis、異步Http、MQTT物聯(lián)網(wǎng)客戶端、異步消息隊(duì)列等眾多高性能組件。
開始實(shí)戰(zhàn)吧!
1.第一步我們先把workerman里需要用到的擴(kuò)展composer下來(lái)吧
"workerman/gateway-worker": "^3.0", "workerman/gatewayclient": "^3.0", "workerman/workerman": "^3.5",
2.第二步我們到官方網(wǎng)站把demo全部下載下來(lái),然后放到我們項(xiàng)目中的目錄
圖片中我就把整個(gè)項(xiàng)目都放在了HTTP/Controller/Workerman中。
3.第三步我們需要把把以下3個(gè)文件的引用部分修改為以下。不然會(huì)報(bào)路徑錯(cuò)誤
start_businessworker,start_gateway,start_register
require_once __DIR__ . '/../../../../../vendor/autoload.php';
4.修改完成后我們就可以在liunx直接運(yùn)行對(duì)應(yīng)的啟動(dòng)文件
php start.php start -d
如果你是在window下就雙擊start_for_win.bat運(yùn)行
5.運(yùn)行成功后,你就應(yīng)該可以看到以下的界面
到此我們搭建基于workerman的通信環(huán)境就已經(jīng)完成。接下來(lái)我們就可以根據(jù)自己的項(xiàng)目需求進(jìn)行開發(fā)。在此向大家重點(diǎn)說(shuō)明。我們所有的聊天是邏輯都在目錄中的Events.php進(jìn)行修改。
---------------------------------華麗分割線---------------------------------------------------
下面我給大家貼一下我編寫的部分份代碼。
Event.php
<?php /** * This file is part of workerman. * * Licensed under The MIT License * For full copyright and license information, please see the MIT-LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @author walkor<walkor@workerman.net> * @copyright walkor<walkor@workerman.net> * @link http://www.workerman.net/ * @license http://www.opensource.org/licenses/mit-license.php MIT License */ /** * 用于檢測(cè)業(yè)務(wù)代碼死循環(huán)或者長(zhǎng)時(shí)間阻塞等問(wèn)題 * 如果發(fā)現(xiàn)業(yè)務(wù)卡死,可以將下面declare打開(去掉//注釋),并執(zhí)行php start.php reload * 然后觀察一段時(shí)間workerman.log看是否有process_timeout異常 */ //declare(ticks=1); /** * 聊天主邏輯 * 主要是處理 onMessage onClose */ use \GatewayWorker\Lib\Gateway; class Events { /** * 作者:何志偉 * 當(dāng)客戶端連接上來(lái)的時(shí)候 * 創(chuàng)建時(shí)間:2018/10/25 * @param $client_id 此ID為gatewayworker 自動(dòng)生成ID */ public static function onConnect($client_id) { Gateway::sendToClient($client_id, json_encode(array( 'type' => 'init', 'client_id' => $client_id ))); } /** * 有消息時(shí) * @param int $client_id * @param mixed $message */ public static function onMessage($client_id, $message) { // debug echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']} client_id:$client_id session:".json_encode($_SESSION)." onMessage:".$message."\n"; // 客戶端傳遞的是json數(shù)據(jù) $message_data = json_decode($message, true); if(!$message_data) { return ; } // 根據(jù)類型執(zhí)行不同的業(yè)務(wù) switch($message_data['type']) { // 客戶端回應(yīng)服務(wù)端的心跳 case 'pong': return; // 客戶端登錄 message格式: {type:login, name:xx, room_id:1} ,添加到客戶端,廣播給所有客戶端xx進(jìn)入聊天室 case 'login': // 判斷是否有房間號(hào) if(!isset($message_data['room_id'])) { throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message"); } // 把房間號(hào)昵稱放到session中 $room_id = $message_data['room_id']; $client_name = htmlspecialchars($message_data['client_name']); $_SESSION['room_id'] = $room_id; $_SESSION['client_name'] = $client_name; // 獲取房間內(nèi)所有用戶列表 $clients_list = Gateway::getClientSessionsByGroup($room_id); foreach($clients_list as $tmp_client_id=>$item) { $clients_list[$tmp_client_id] = $item['client_name']; } // $clients_list[$client_id] = $client_name; // 轉(zhuǎn)播給當(dāng)前房間的所有客戶端,xx進(jìn)入聊天室 message {type:login, client_id:xx, name:xx} $new_message = array('type'=>$message_data['type'], 'client_id'=>$client_id, 'client_name'=>htmlspecialchars($client_name), 'time'=>date('Y-m-d H:i:s'),'to'=>$message_data['to'],'room_id'=>$message_data['room_id'], 'from'=>$message_data['from'],'tag'=>$message_data['tag']); Gateway::sendToGroup($room_id, json_encode($new_message)); Gateway::joinGroup($client_id, $room_id); // 給當(dāng)前用戶發(fā)送用戶列表 $new_message['client_list'] = $clients_list; Gateway::sendToCurrentClient(json_encode($new_message)); return; // 客戶端發(fā)言 message: {type:say, to_client_id:xx, content:xx} case 'say': // 非法請(qǐng)求 if(!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $client_name = $_SESSION['client_name']; // 私聊 // if($message_data['to_client_id'] != 'all') // { // $new_message = array( // 'type'=>'say', // 'from_client_id'=>$client_id, // 'from_client_name' =>$client_name, // 'to_client_id'=>$message_data['to_client_id'], // 'content'=>"<b>對(duì)你說(shuō): </b>".nl2br(htmlspecialchars($message_data['content'])), // 'time'=>date('Y-m-d H:i:s'), // ); // Gateway::sendToClient($message_data['to_client_id'], json_encode($new_message)); // $new_message['content'] = "<b>你對(duì)".htmlspecialchars($message_data['to_client_name'])."說(shuō): </b>".nl2br(htmlspecialchars($message_data['content'])); // return Gateway::sendToCurrentClient(json_encode($new_message)); // } $new_message = array( 'type'=>'say', 'from_client_id'=>$client_id, 'from_client_name' =>$client_name, 'to_client_id'=>'all', 'content'=>nl2br(htmlspecialchars($message_data['content'])), 'time'=>date('Y-m-d H:i:s'), ); return Gateway::sendToGroup($room_id ,json_encode($new_message)); } } /** * 當(dāng)客戶端斷開連接時(shí) * @param integer $client_id 客戶端id */ public static function onClose($client_id) { // debug echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']} client_id:$client_id onClose:''\n"; // 從房間的客戶端列表中刪除 if(isset($_SESSION['room_id'])) { $room_id = $_SESSION['room_id']; $new_message = array('type'=>'logout', 'from_client_id'=>$client_id, 'from_client_name'=>$_SESSION['client_name'], 'time'=>date('Y-m-d H:i:s')); Gateway::sendToGroup($room_id, json_encode($new_message)); } } }
客戶端頁(yè)面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>與{{$to->name}}的對(duì)話</title> <script type="text/javascript" src="{{asset('js')}}/swfobject.js"></script> <script type="text/javascript" src="{{asset('js')}}/web_socket.js"></script> <script type="text/javascript" src="{{asset('js')}}/jquery.min.js"></script> <link href="{{asset('css')}}/jquery-sinaEmotion-2.1.0.min.css" rel="external nofollow" rel="stylesheet"> <link href="{{asset('css')}}/bootstrap.min.css" rel="external nofollow" rel="stylesheet"> <link href="{{asset('css')}}/style.css" rel="external nofollow" rel="stylesheet"> <script type="text/javascript" src="{{asset('js')}}/jquery-sinaEmotion-2.1.0.min.js"></script> {{--<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>--}} </head> <style> #sinaEmotion { z-index: 999; width: 373px; padding: 10px; display: none; font-size: 12px; background: #fff; overflow: hidden; position: absolute; border: 1px solid #e8e8e8; top: 100px; left: 542.5px; } </style> <body onload="connect();" style="margin: auto; text-align: center;"> <div style="margin: auto;"> <div style="border: 1px solid red; height: 40px; width: 500px; margin: auto;"> {{--對(duì)話窗口頭部--}} <div> <div style="width: 80px; height: 40px; border: 1px solid blue; float: left"> <img src="{{$to->heading}}" width="80px" height="40px"> </div> <div style="width: 150px; height: 40px; border: 1px solid blue; float: left"> {{$to->name}} </div> </div> {{--//對(duì)話窗口內(nèi)容--}} <div class="content" style="width: 500px; height: 400px; border: 1px solid green; margin-top: 40px; overflow-y: auto"> {{--對(duì)方的頭像與文字--}} {{--<div style="min-height: 50px;margin-top: 10px;">--}} {{--<div style="width: 50px;height: 50px; border: 1px solid red; margin-left:10px; float: left">--}} {{--<img src="{{$to->heading}}" width="50px" height="50px">--}} {{--</div>--}} {{--<div style="border: 1px solid red; float: left; min-height: 50px" >dsadsadsadsadsa</div>--}} {{--</div>--}} {{--我的頭像與文字--}} {{--<div style= "min-height:50px;margin-top: 10px;">--}} {{--<div style="width: 50px;height: 50px; border: 1px solid red; margin-left:10px; float: right">--}} {{--<img src="{{$from->heading}}" width="50px" height="50px">--}} {{--</div>--}} {{--<div style="border: 1px solid red; float: right; min-height: 50px" >dsadsadsadsadsa</div>--}} {{--</div>--}} </div> {{--對(duì)話發(fā)送窗口--}} <form onsubmit="return onSubmit(); return false;" id="ajaxfrom"> <input type="hidden" name="to" value="{{$to->id}}"> <input type="hidden" name="from" value="{{$from->id}}"> <input type="hidden" name="room_id" value="{{$room}}"> <input type="hidden" name="tag" value="{{$tag}}"> <textarea id="textarea" name="content" class="Input_text" style="margin: 0px; width: 501px; height: 213px;"></textarea> <div class="say-btn"> <input type="button" class="btn btn-default face pull-left" value="表情" /> <button type="submit" class="btn btn-default">發(fā)表</button> </div> </form> 房間號(hào){{$room}} </div> </div> </body> </html> <script type="text/javascript"> if (typeof console == "undefined") { this.console = { log: function (msg) { } };} // 如果瀏覽器不支持websocket,會(huì)使用這個(gè)flash自動(dòng)模擬websocket協(xié)議,此過(guò)程對(duì)開發(fā)者透明 WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf"; // 開啟flash的websocket debug WEB_SOCKET_DEBUG = true; var ws, name, client_list={}; var to_client_id=""; // 連接服務(wù)端初始化函數(shù) function connect() { // 創(chuàng)建websocket 屆時(shí)可以替換為對(duì)應(yīng)的服務(wù)器地址 ws = new WebSocket("ws://"+document.domain+":7272"); // 當(dāng)socket連接打開時(shí),輸入用戶名 ws.onopen = onopen; // 當(dāng)有消息時(shí)根據(jù)消息類型顯示不同信息 ws.onmessage = onmessage; //當(dāng)連接丟失時(shí),調(diào)用連接方法嘗試重新連接 ws.onclose = function() { console.log("連接關(guān)閉,定時(shí)重連"); connect(); }; //當(dāng)操作報(bào)錯(cuò)時(shí),返回異常錯(cuò)誤 ws.onerror = function() { console.log("出現(xiàn)錯(cuò)誤"); }; //發(fā)送ajax獲取當(dāng)前房間的通話記錄 $.post("/get_record", { "room":"{{$room}}" }, function(msg){ $.each(msg,function (v,k) { console.log(k); //判斷 if(k.tag!="{{$tag}}"){ $(".content").append( '<div style="min-height: 50px;margin-top: 10px;">' + '<div style="width: 50px;height: 50px; border: 1px solid red; margin-left:10px; float: left">'+ '<img src="{{$to->heading}}" width="50px" height="50px">'+ '</div>'+ '<div style="border: 1px solid red; float: left; min-height: 50px" >'+k.content+'</div>'+ '<div>' ).parseEmotion(); }else{ $(".content").append( '<div style="min-height: 50px;margin-top: 10px;">' + '<div style="width: 50px;height: 50px; border: 1px solid red; margin-left:10px; float: right">'+ '<img src="{{$from->heading}}" width="50px" height="50px">'+ '</div>'+ '<div style="border: 1px solid red; float: right; min-height: 50px" >'+k.content+'</div>'+ '<div>' ).parseEmotion(); } }) }); } // 連接建立時(shí)發(fā)送登錄信息 function onopen() { var login_data='{"type":"login","client_name":"{{$from->name}}","room_id":"{{$room}}","to":"{{$to->id}}","from":"{{$from->id}}","tag":"{{$tag}}"}'; ws.send(login_data); console.log('登錄成功') } // 服務(wù)端發(fā)來(lái)消息時(shí) function onmessage(e) { var data = JSON.parse(e.data); switch(data['type']){ // 服務(wù)端ping客戶端心跳 case 'ping': ws.send('{"type":"pong"}'); break; // 登錄 更新用戶列表 case 'login': //講需要的發(fā)送ID保存到本地to_client_id變量中 for(var p in data['client_list']){ to_client_id=p; } console.log(to_client_id); break; // 發(fā)言 case 'say': console.log(data); say(data['from_client_id'], data['from_client_name'], data['content'], data['time']); break; // 用戶退出 更新用戶列表 case 'logout': console.log(data); break; case 'init': //此處可以發(fā)送ajax用于綁定不同的用戶ID和client console.log(data); break; } } // 提交對(duì)話 function onSubmit() { //先檢查當(dāng)前的對(duì)話是否超過(guò)20條記錄數(shù) var count=true; //發(fā)送ajax獲取當(dāng)前房間的通話記錄 $.ajax({ url: "/check_count", type: "post", async:false, // cache: false, // contentType: false, // processData: false, data:{ 'room':"1", }, success: function (msg) { if(msg>10){ alert('當(dāng)前的對(duì)話已經(jīng)超過(guò)次數(shù),請(qǐng)購(gòu)買對(duì)應(yīng)服務(wù)') count=false; } } }); if(count){ var neirong=$("#textarea").val().replace(/"/g, '\\"').replace(/\n/g,'\\n').replace(/\r/g, '\\r'); //ajax先把對(duì)應(yīng)的內(nèi)容發(fā)送到后臺(tái)錄入,回調(diào)成功后才把信息發(fā)送 var fm=$("#ajaxfrom")[0]; var formData = new FormData(fm); $.ajax({ url: "/record", type: "post", cache: false, contentType: false, processData: false, data: formData, beforeSend:function(){ }, success: function (msg) { if(msg.code=="0"){ ws.send('{"type":"say","to_client_id":"all","to_client_name":"{{$to->name}}","content":"'+neirong+'"}'); //清空文本框內(nèi)容 $("#textarea").val(""); //強(qiáng)制定位光標(biāo) $("#textarea").focus(); }else{ } } }); } return false; } // 發(fā)言 function say(from_client_id, from_client_name, content, time){ //判斷當(dāng)前的用戶名稱與發(fā)送消息的名稱是否一致 if( "{{$from->name}}" == from_client_name){ $(".content").append( '<div style="min-height: 50px;margin-top: 10px;">' + '<div style="width: 50px;height: 50px; border: 1px solid red; margin-left:10px; float: right">'+ '<img src="{{$from->heading}}" width="50px" height="50px">'+ '</div>'+ '<div style="border: 1px solid red; float: right; min-height: 50px" >'+content+'</div>'+ '<div>' ).parseEmotion(); }else{ $(".content").append( '<div style="min-height: 50px;margin-top: 10px;">' + '<div style="width: 50px;height: 50px; border: 1px solid red; margin-left:10px; float: left">'+ '<img src="{{$to->heading}}" width="50px" height="50px">'+ '</div>'+ '<div style="border: 1px solid red; float: left; min-height: 50px" >'+content+'</div>'+ '<div>' ).parseEmotion(); } // $("#dialog").append('<div class="speech_item"><img src="http://lorempixel.com/38/38/?'+from_client_id+'" class="user_icon" /> '+from_client_name+' <br> '+time+'<div style="clear:both;"></div><p class="triangle-isosceles top">'+content+'</p> </div>').parseEmotion(); } $(function(){ //全局用戶ID select_client_id = 'all'; //如果發(fā)送的用戶有變化則對(duì)應(yīng)的用戶ID進(jìn)行替換 $("#client_list").change(function(){ select_client_id = $("#client_list option:selected").attr("value"); }); //表情選擇 $('.face').click(function(event){ $(this).sinaEmotion(); event.stopPropagation(); }); }); // document.write('<meta name="viewport" content="width=device-width,initial-scale=1">'); $("textarea").on("keydown", function(e) { //按enter鍵自動(dòng)提交 if(e.keyCode === 13 && !e.ctrlKey) { e.preventDefault(); $('form').submit(); return false; } // 按ctrl+enter組合鍵換行 if(e.keyCode === 13 && e.ctrlKey) { $(this).val(function(i,val){ return val + "\n"; }); } }); </script>
這兩個(gè)代碼片段其實(shí)就是主要運(yùn)行的核心片段。其他框架的自帶參數(shù)需要各位自己去根據(jù)文檔去調(diào)試優(yōu)化。到此基于workerman的聊天用于功能demo已經(jīng)搭建完畢。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
在thinkphp5.0路徑中實(shí)現(xiàn)去除index.php的方式
今天小編就為大家分享一篇在thinkphp5.0路徑中實(shí)現(xiàn)去除index.php的方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-10-10PHP超全局?jǐn)?shù)組(Superglobals)介紹
這篇文章主要介紹了PHP超全局?jǐn)?shù)組(Superglobals)介紹,本文講解了概述、變量的作用域、超全局?jǐn)?shù)組及注意事項(xiàng)等內(nèi)容,需要的朋友可以參考下2015-07-07Laravel5.1 框架關(guān)聯(lián)模型之后操作實(shí)例分析
這篇文章主要介紹了Laravel5.1 框架關(guān)聯(lián)模型之后操作,結(jié)合實(shí)例形式分析了laravel5.1框架寫入關(guān)聯(lián)模型、更新關(guān)聯(lián)關(guān)系等相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2020-01-01php實(shí)例分享之通過(guò)遞歸實(shí)現(xiàn)刪除目錄下的所有文件詳解
最近遇到一個(gè)實(shí)際問(wèn)題,需要清空制定目錄下的所有文件及清空數(shù)據(jù)庫(kù)。清空數(shù)據(jù)庫(kù)不難,但要如何遞歸刪除一個(gè)目錄下的所有文件呢。 于是去網(wǎng)上研究了下資料再加上自己琢磨解決了這一問(wèn)題。2014-05-05ThinkPHP3.2.3框架Memcache緩存使用方法實(shí)例總結(jié)
這篇文章主要介紹了ThinkPHP3.2.3框架Memcache緩存使用方法,結(jié)合實(shí)例形式總結(jié)分析看thinkPHP框架下Memcache緩存各種調(diào)用方法與配置相關(guān)操作技巧,需要的朋友可以參考下2019-04-04php curl抓取網(wǎng)頁(yè)的介紹和推廣及使用CURL抓取淘寶頁(yè)面集成方法
抓取網(wǎng)頁(yè)內(nèi)容,分析網(wǎng)頁(yè)數(shù)據(jù)經(jīng)常使用php curl,簡(jiǎn)潔易用,本篇文章通過(guò)代碼實(shí)例給大家講解 php curl抓取網(wǎng)頁(yè)的介紹和推廣及使用CURL抓取淘寶頁(yè)面集成方法,需要的朋友參考下2015-11-11ECshop 遷移到 PHP7版本時(shí)遇到的兼容性問(wèn)題
最近有網(wǎng)友問(wèn)我在php7上安裝ecshopv2.7.3時(shí),報(bào)錯(cuò),究竟了半天沒有找到原因,下面由腳本之家小編給大家分析此問(wèn)題出現(xiàn)的原因2016-02-02PHP加密擴(kuò)展庫(kù)Mcrypt安裝和實(shí)例
PHP加密擴(kuò)展庫(kù)有Mcrypt和Mhash,其中,Mcrypt擴(kuò)展庫(kù)可以實(shí)現(xiàn)加密解密功能,今天我我們講的就是Mcrypt的功能和實(shí)例2013-11-11