Workerman是一款 开源 高性能异步 PHP socket即时通讯框架 。支持高并发,超高稳定性,被广泛的用于手机app、移动通讯,微信小程序,手游服务端、网络游戏、PHP聊天室、硬件通讯、智能家居、车联网、物联网等领域的开发。 支持TCP长连接,支持Websocket、HTTP等协议,支持自定义协议。拥有异步Mysql、异步Redis、异步Http、MQTT物联网客户端、异步消息队列等众多高性能组件。
搭建步骤
1.第一步我们先把workerman里需要用到的扩展composer下来吧

"workerman/gateway-worker":"^3.0","workerman/gatewayclient":"^3.0","workerman/workerman":"^3.5",
2.第二步到官方网站把demo全部下载下来,然后放到我们项目中的目录
图片中我就把整个项目都放在了HTTP/Controller/Workerman中。
3.第三步我们需要把把以下3个文件的引用部分修改为以下。不然会报路径错误
start_businessworker,start_gateway,start_register
require_once__DIR__.'/../../../../../vendor/autoload.php';
4.修改完成后我们就可以在liunx直接运行对应的启动文件
phpstart.phpstart-d
如果你是在window下就双击start_for_win.bat运行
5.运行成功后,你就应该可以看到以下的界面
到此我们搭建基于workerman的通信环境就已经完成。接下来我们就可以根据自己的项目需求进行开发。在此向大家重点说明。我们所有的聊天是逻辑都在目录中的Events.php进行修改。
下面我给大家贴一下我编写的部分份代码。
Event.php
<?php/Thisfileispartofworkerman.LicensedunderTheMITLicenseForfullcopyrightandlicenseinformation,pleaseseetheMIT-LICENSE.txtRedistributionsoffilesmustretaintheabovecopyrightnotice.@authorwalkor<walkor@workerman.net>@copyrightwalkor<walkor@workerman.net>@linkhttp://www.workerman.net/@licensehttp://www.opensource.org/licenses/mit-license.phpMITLicense//用于检测业务代码死循环或者长时间阻塞等问题如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行phpstart.phpreload然后观察一段时间workerman.log看是否有process_timeout异常///declare(ticks=1);/聊天主逻辑主要是处理onMessageonClose/use\GatewayWorker\Lib\Gateway;classEvents{/作者:何志伟当客户端连接上来的时候创建时间:2018/10/25@param$client_id此ID为gatewayworker自动生成ID/publicstaticfunctiononConnect($client_id){Gateway::sendToClient($client_id,json_encode(array('type'=>'init','client_id'=>$client_id)));}/有消息时@paramint$client_id@parammixed$message/publicstaticfunctiononMessage($client_id,$message){//debugecho"client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']}gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}client_id:$client_idsession:".json_encode($_SESSION)."onMessage:".$message."\n";//客户端传递的是json数据$message_data=json_decode($message,true);if(!$message_data){return;}//根据类型执行不同的业务switch($message_data['type']){//客户端回应服务端的心跳case'pong':return;//客户端登录message格式:{type:login,name:xx,room_id:1},添加到客户端,广播给所有客户端xx进入聊天室case'login'://判断是否有房间号if(!isset($message_data['room_id'])){thrownew\Exception("\$message_data['room_id']notset.client_ip:{$_SERVER['REMOTE_ADDR']}\$message:$message");}//把房间号昵称放到session中$room_id=$message_data['room_id'];$client_name=htmlspecialchars($message_data['client_name']);$_SESSION['room_id']=$room_id;$_SESSION['client_name']=$client_name;//获取房间内所有用户列表$clients_list=Gateway::getClientSessionsByGroup($room_id);foreach($clients_listas$tmp_client_id=>$item){$clients_list[$tmp_client_id]=$item['client_name'];}//$clients_list[$client_id]=$client_name;//转播给当前房间的所有客户端,xx进入聊天室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-dH: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);//给当前用户发送用户列表$new_message['client_list']=$clients_list;Gateway::sendToCurrentClient(json_encode($new_message));return;//客户端发言message:{type:say,to_client_id:xx,content:xx}case'say'://非法请求if(!isset($_SESSION['room_id'])){thrownew\Exception("\$_SESSION['room_id']notset.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>对你说:</b>".nl2br(htmlspecialchars($message_data['content'])),//'time'=>date('Y-m-dH:i:s'),//);//Gateway::sendToClient($message_data['to_client_id'],json_encode($new_message));//$new_message['content']="<b>你对".htmlspecialchars($message_data['to_client_name'])."说:</b>".nl2br(htmlspecialchars($message_data['content']));//returnGateway::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-dH:i:s'),);returnGateway::sendToGroup($room_id,json_encode($new_message));}}/当客户端断开连接时@paraminteger$client_id客户端id/publicstaticfunctiononClose($client_id){//debugecho"client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']}gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}client_id:$client_idonClose:''\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-dH:i:s'));Gateway::sendToGroup($room_id,json_encode($new_message));}}}
客户端页面
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>与{{$to->name}}的对话</title><scripttype="text/javascript"src="{{asset('js')}}/swfobject.js"></script><scripttype="text/javascript"src="{{asset('js')}}/web_socket.js"></script><scripttype="text/javascript"src="{{asset('js')}}/jquery.min.js"></script><linkhref="{{asset('css')}}/jquery-sinaEmotion-2.1.0.min.css"rel="externalnofollow"rel="stylesheet"><linkhref="{{asset('css')}}/bootstrap.min.css"rel="externalnofollow"rel="stylesheet"><linkhref="{{asset('css')}}/style.css"rel="externalnofollow"rel="stylesheet"><scripttype="text/javascript"src="{{asset('js')}}/jquery-sinaEmotion-2.1.0.min.js"></script>{{--<scriptsrc="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:1pxsolid#e8e8e8;top:100px;left:542.5px;}</style><bodyonload="connect();"style="margin:auto;text-align:center;"><divstyle="margin:auto;"><divstyle="border:1pxsolidred;height:40px;width:500px;margin:auto;">{{--对话窗口头部--}}<div><divstyle="width:80px;height:40px;border:1pxsolidblue;float:left"><imgsrc="{{$to->heading}}"width="80px"height="40px"></div><divstyle="width:150px;height:40px;border:1pxsolidblue;float:left">{{$to->name}}</div></div>{{--//对话窗口内容--}}<divclass="content"style="width:500px;height:400px;border:1pxsolidgreen;margin-top:40px;overflow-y:auto">{{--对方的头像与文字--}}{{--<divstyle="min-height:50px;margin-top:10px;">--}}{{--<divstyle="width:50px;height:50px;border:1pxsolidred;margin-left:10px;float:left">--}}{{--<imgsrc="{{$to->heading}}"width="50px"height="50px">--}}{{--</div>--}}{{--<divstyle="border:1pxsolidred;float:left;min-height:50px">dsadsadsadsadsa</div>--}}{{--</div>--}}{{--我的头像与文字--}}{{--<divstyle="min-height:50px;margin-top:10px;">--}}{{--<divstyle="width:50px;height:50px;border:1pxsolidred;margin-left:10px;float:right">--}}{{--<imgsrc="{{$from->heading}}"width="50px"height="50px">--}}{{--</div>--}}{{--<divstyle="border:1pxsolidred;float:right;min-height:50px">dsadsadsadsadsa</div>--}}{{--</div>--}}</div>{{--对话发送窗口--}}<formonsubmit="returnonSubmit();returnfalse;"id="ajaxfrom"><inputtype="hidden"name="to"value="{{$to->id}}"><inputtype="hidden"name="from"value="{{$from->id}}"><inputtype="hidden"name="room_id"value="{{$room}}"><inputtype="hidden"name="tag"value="{{$tag}}"><textareaid="textarea"name="content"class="Input_text"style="margin:0px;width:501px;height:213px;"></textarea><divclass="say-btn"><inputtype="button"class="btnbtn-defaultfacepull-left"value="表情"/><buttontype="submit"class="btnbtn-default">发表</button></div></form>房间号{{$room}}</div></div></body></html><scripttype="text/javascript">if(typeofconsole=="undefined"){this.console={log:function(msg){}};}//如果浏览器不支持websocket,会使用这个flash自动模拟websocket协议,此过程对开发者透明WEB_SOCKET_SWF_LOCATION="/swf/WebSocketMain.swf";//开启flash的websocketdebugWEB_SOCKET_DEBUG=true;varws,name,client_list={};varto_client_id="";//连接服务端初始化函数functionconnect(){//创建websocket届时可以替换为对应的服务器地址ws=newWebSocket("ws://"+document.domain+":7272");//当socket连接打开时,输入用户名ws.onopen=onopen;//当有消息时根据消息类型显示不同信息ws.onmessage=onmessage;//当连接丢失时,调用连接方法尝试重新连接ws.onclose=function(){console.log("连接关闭,定时重连");connect();};//当操作报错时,返回异常错误ws.onerror=function(){console.log("出现错误");};//发送ajax获取当前房间的通话记录$.post("/get_record",{"room":"{{$room}}"},function(msg){$.each(msg,function(v,k){console.log(k);//判断if(k.tag!="{{$tag}}"){$(".content").append('<divstyle="min-height:50px;margin-top:10px;">'+'<divstyle="width:50px;height:50px;border:1pxsolidred;margin-left:10px;float:left">'+'<imgsrc="{{$to->heading}}"width="50px"height="50px">'+'</div>'+'<divstyle="border:1pxsolidred;float:left;min-height:50px">'+k.content+'</div>'+'<div>').parseEmotion();}else{$(".content").append('<divstyle="min-height:50px;margin-top:10px;">'+'<divstyle="width:50px;height:50px;border:1pxsolidred;margin-left:10px;float:right">'+'<imgsrc="{{$from->heading}}"width="50px"height="50px">'+'</div>'+'<divstyle="border:1pxsolidred;float:right;min-height:50px">'+k.content+'</div>'+'<div>').parseEmotion();}})});}//连接建立时发送登录信息functiononopen(){varlogin_data='{"type":"login","client_name":"{{$from->name}}","room_id":"{{$room}}","to":"{{$to->id}}","from":"{{$from->id}}","tag":"{{$tag}}"}';ws.send(login_data);console.log('登录成功')}//服务端发来消息时functiononmessage(e){vardata=JSON.parse(e.data);switch(data['type']){//服务端ping客户端心跳case'ping':ws.send('{"type":"pong"}');break;//登录更新用户列表case'login'://讲需要的发送ID保存到本地to_client_id变量中for(varpindata['client_list']){to_client_id=p;}console.log(to_client_id);break;//发言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'://此处可以发送ajax用于绑定不同的用户ID和clientconsole.log(data);break;}}//提交对话functiononSubmit(){//先检查当前的对话是否超过20条记录数varcount=true;//发送ajax获取当前房间的通话记录$.ajax({url:"/check_count",type:"post",async:false,//cache:false,//contentType:false,//processData:false,data:{'room':"1",},success:function(msg){if(msg>10){alert('当前的对话已经超过次数,请购买对应服务')count=false;}}});if(count){varneirong=$("#textarea").val().replace(/"/g,'\\"').replace(/\n/g,'\\n').replace(/\r/g,'\\r');//ajax先把对应的内容发送到后台录入,回调成功后才把信息发送varfm=$("#ajaxfrom")[0];varformData=newFormData(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+'"}');//清空文本框内容$("#textarea").val("");//强制定位光标$("#textarea").focus();}else{}}});}returnfalse;}//发言functionsay(from_client_id,from_client_name,content,time){//判断当前的用户名称与发送消息的名称是否一致if("{{$from->name}}"==from_client_name){$(".content").append('<divstyle="min-height:50px;margin-top:10px;">'+'<divstyle="width:50px;height:50px;border:1pxsolidred;margin-left:10px;float:right">'+'<imgsrc="{{$from->heading}}"width="50px"height="50px">'+'</div>'+'<divstyle="border:1pxsolidred;float:right;min-height:50px">'+content+'</div>'+'<div>').parseEmotion();}else{$(".content").append('<divstyle="min-height:50px;margin-top:10px;">'+'<divstyle="width:50px;height:50px;border:1pxsolidred;margin-left:10px;float:left">'+'<imgsrc="{{$to->heading}}"width="50px"height="50px">'+'</div>'+'<divstyle="border:1pxsolidred;float:left;min-height:50px">'+content+'</div>'+'<div>').parseEmotion();}//$("#dialog").append('<divclass="speech_item"><imgsrc="http://lorempixel.com/38/38/?'+from_client_id+'"class="user_icon"/>'+from_client_name+'<br>'+time+'<divstyle="clear:both;"></div><pclass="triangle-isoscelestop">'+content+'</p></div>').parseEmotion();}$(function(){//全局用户IDselect_client_id='all';//如果发送的用户有变化则对应的用户ID进行替换$("#client_list").change(function(){select_client_id=$("#client_listoption:selected").attr("value");});//表情选择$('.face').click(function(event){$(this).sinaEmotion();event.stopPropagation();});});//document.write('<metaname="viewport"content="width=device-width,initial-scale=1">');$("textarea").on("keydown",function(e){//按enter键自动提交if(e.keyCode===13&&!e.ctrlKey){e.preventDefault();$('form').submit();returnfalse;}//按ctrl+enter组合键换行if(e.keyCode===13&&e.ctrlKey){$(this).val(function(i,val){returnval+"\n";});}});</script>
上面是主要运行的核心代码。其他框架的自带参数需要各位自己去根据文档去调试优化。到此基于workerman的聊天用于功能demo已经搭建完毕。
领取方式:点赞关注1 ThinkPHP5底层源码分析视频教程
2 PHP7入门到进阶_难得的好教程
3 2020-Laravel6实战视频教程
4 Restful Api实战演练
5 WebSocket网络实战2020最新版
视频教程不是给你收藏的,希望对提升你的学习技能有些许帮助吧!领取方式:点赞关注小编后私信【资料】获取资料领取方式!