用php+swoole+redis 簡(jiǎn)單實(shí)現(xiàn)網(wǎng)頁(yè)即時(shí)聊天,需要瀏覽器支持html5的websocket,
websocket是不同于http的另外一種網(wǎng)絡(luò)通信協(xié)議,能夠進(jìn)行雙向通信,基于此,可開(kāi)發(fā)出各種實(shí)時(shí)通信產(chǎn)品,簡(jiǎn)單做了個(gè)聊天demo,順便分享一下
效果圖如下:
環(huán)境:
參考文檔:
IP與端口:
服務(wù)器端代碼 websocket.php
<?php class Server { private $serv; private $conn=null; private static $fd=null; public function __construct() { $this->redis_connect(); $this->serv=new swoole_websocket_server("0.0.0.0", 9502); $this->serv->set(array( 'worker_num'=> 8, 'daemonize'=> false, 'max_request'=> 10000, 'dispatch_mode'=> 2, 'debug_mode'=> 1 )); echo "start \n"; $this->serv->on('Open', array($this, 'onOpen')); $this->serv->on('Message', array($this, 'onMessage')); $this->serv->on('Close', array($this, 'onClose')); $this->serv->start(); } function onOpen($server, $req) { echo "connection open: {$req->fd} \n"; // $server->push($req->fd, json_encode(33)); } public function onMessage($server, $frame) { //echo "received data $frame->data \n"; //$server->push($frame->fd, json_encode(["hello", "world"])); $pData=json_decode($frame->data,true); $fd=$frame->fd; if(empty($pData)){ echo "received data null \n"; return; } echo "received fd=>{$fd} message: {$frame->data}\n"; $data=[]; if (isset($pData['content'])) { $f_fd=$this->getFd($pData['fid']); //獲取綁定的fd $data=$this->add($pData['uid'], $pData['fid'], $pData['content']); //保存消息 $server->push($f_fd, json_encode($data)); //推送到接收者 $json_data=json_encode($data); echo "推送到接收者 fd=>{$f_fd} message: {$json_data}\n"; } else { $this->unBind($pData['uid']); //首次接入,清除綁定數(shù)據(jù) if ($this->bind($pData['uid'], $fd)) { //綁定fd $data=$this->loadHistory($pData['uid'], $pData['fid']); //加載歷史記錄 } else { $data=array("content"=> "無(wú)法綁定fd"); } } $json_data=json_encode($data); echo "推送到發(fā)送者 fd=>{$fd} message: {$json_data}\n"; $server->push($fd, json_encode($data)); //推送到發(fā)送者 } public function onClose($server, $fd) { //$this->unBind($fd); echo "connection close: {$fd}\n"; } /*******************/ /** * redis * @param string $host * @param string $port * @return bool */ function redis_connect($host='127.0.0.1',$port='6379') { $this->conn=new Redis(); try{ $this->conn->connect($host, $port); }catch (\Exception $e){ user_error(print_r($e)); } return true; } /** * 保存消息 * @param $uid 發(fā)送者uid * @param $fid 接收者uid * @param $content 內(nèi)容 * @return array */ public function add($uid, $fid, $content) { $msg_data=[]; $msg_data['uid']=$uid; $msg_data['fid']=$fid; $msg_data['content']=$content; $msg_data['time']=time(); $key=K::KEY_MSG; $data=$this->conn->get($key); if(!empty($data)){ $data=json_decode($data,true); }else{ $data=[]; } $data[]=$msg_data; $this->conn->set($key,json_encode($data)); $return_msg[]=$msg_data; return $return_msg; } /** * 綁定FD * @param $uid * @param $fd * @return bool */ public function bind($uid, $fd) { $key=K::KEY_UID."{$uid}"; $ret=$this->conn->set($key,$fd); if(!$ret){ echo "bind fail \n"; return false; } return true; } /** * 獲取FD * @param $uid * @return mixed */ public function getFd($uid) { $key=K::KEY_UID."{$uid}"; $fd=$this->conn->get($key); return $fd; } /** * 清除綁定 * @param $uid * @return bool */ public function unBind($uid) { $key=K::KEY_UID."{$uid}"; $ret=$this->conn->delete($key); if(!$ret){ return false; } return true; } /** * 歷史記錄 * @param $uid * @param $fid * @param null $id * @return array */ public function loadHistory($uid, $fid) { $msg_data=[]; $key=K::KEY_MSG; $this->conn->delete($key); $data=$this->conn->get($key); if($data){ echo $data; $json_data=json_decode($data,true); foreach ($json_data as $k=>$info){ if(($info['uid']==$uid&&$info['fid']==$fid)||($info['uid']==$fid&&$info['fid']==$uid)){ $msg_data[]=$info; } } } return $msg_data; } } //Key 定義 class K{ const KEY_MSG='msg_data'; const KEY_FD='fd_data'; const KEY_UID='uid'; } //啟動(dòng)服務(wù)器 $server=new Server();
客戶端代碼 chat.html
<!DOCTYPE html> <html lang="en"> <html> <head> <title>CHAT A</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="jquery.min.js"></script> <script src="jquery.json.min.js"></script> <style type="text/css"> .talk_con{ width:600px; height:500px; border:1px solid #666; margin:50px auto 0; background:#f9f9f9; } .talk_show{ width:580px; height:420px; border:1px solid #666; background:#fff; margin:10px auto 0; overflow:auto; } .talk_input{ width:580px; margin:10px auto 0; } .whotalk{ width:80px; height:30px; float:left; outline:none; } .talk_word{ width:420px; height:26px; padding:0px; float:left; margin-left:10px; outline:none; text-indent:10px; } .talk_sub{ width:56px; height:30px; float:left; margin-left:10px; } .close{ width:56px; height:30px; float:left; margin-left:10px; } .atalk{ margin:10px; } .atalk span{ display:inline-block; background:#0181cc; border-radius:10px; color:#fff; padding:5px 10px; } .btalk{ margin:10px; text-align:right; } .btalk span{ display:inline-block; background:#ef8201; border-radius:10px; color:#fff; padding:5px 10px; } </style> <script type="text/javascript"> var uid='A'; //發(fā)送者uid var fid='B'; //接收者uid var wsUrl='ws://192.168.1.100:9502'; var webSocket=new WebSocket(wsUrl); //創(chuàng)建Socket webSocket.onopen=function (event) { console.log('onOpen=' + event.data); //webSocket.send("hello webSocket"); initData(); //初始化數(shù)據(jù),加載歷史記錄 }; //接收數(shù)據(jù)事件 webSocket.onmessage=function (event) { console.log('onMessage=' + event.data); loadData($.parseJSON(event.data)); //導(dǎo)入消息記錄,加載新的消息 } //關(guān)閉socket webSocket.onclose=function (event) { console.log('close'); }; //socket連接錯(cuò)誤 webSocket.onerror=function (event) { console.log('error-data:' + event.data); } //========================================================//向服務(wù)器發(fā)送數(shù)據(jù) function sendMsg() { var pData={ content: document.getElementById('content').value, uid: uid, fid: fid, } if (pData.content=='') { alert("消息不能為空"); return; } webSocket.send($.toJSON(pData)); //發(fā)送消息 } function initData() { //var Who=document.getElementById("who").value; console.log('initData uid:' + uid + ' fid:'+fid); var pData={ uid: uid, fid: fid, } webSocket.send($.toJSON(pData)); //獲取消息記錄,綁定fd var html='<div class="atalk"><span id="asay">' + 'WebSocket連接成功' + '</div>'; $("#words").append(html); } function loadData(data) { for (var i=0; i < data.length; i++) { if(data[i].uid=='A'){ var html='<div class="atalk"><span id="asay">' + data[i].uid + '說(shuō): ' + data[i].content + '</div>'; }else{ var html='<div class="btalk"><span id="asay">' + data[i].uid + '說(shuō): ' + data[i].content + '</div>'; } $("#words").append(html); } } //關(guān)閉連接 function closeWebSocket() { console.log('close'); webSocket.close(); var html='<div class="atalk"><span id="asay">' + '已和服務(wù)器斷開(kāi)連接' + '</div>'; $("#words").append(html); } </script> </head> <body> <div class="talk_con"> <div class="talk_show" id="words"> <!--<div class="atalk"><span id="asay">A說(shuō):吃飯了嗎?</span></div>--> <!--<div class="btalk"><span id="bsay">B說(shuō):還沒(méi)呢,你呢?</span></div>--> </div> <div class="talk_input"> <!--<select class="whotalk" id="who">--> <!--<option value="A" selected="selected">A說(shuō):</option>--> <!--<option value="B">B說(shuō):</option>--> <!--</select>--> <button class="close" onclick="closeWebSocket()">斷開(kāi)</button> <input type="text" class="talk_word" id="content"> <input type="button" onclick="sendMsg()" value="發(fā)送" class="talk_sub" id="talksub"> </div> </div> </body> </html>
文件詳情:
使用方法:
安裝完php、redis和swoole擴(kuò)展之后,直接執(zhí)行:
并可以觀察下輸出,看看websocket服務(wù)器是否正常
么是Workerman?
Workerman是一款 開(kāi)源 高性能異步 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)域的開(kāi)發(fā)。 支持TCP長(zhǎng)連接,支持Websocket、HTTP等協(xié)議,支持自定義協(xié)議。擁有異步Mysql、異步Redis、異步Http、MQTT物聯(lián)網(wǎng)客戶端、異步消息隊(duì)列等眾多高性能組件。
搭建步驟
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)行開(kāi)發(fā)。在此向大家重點(diǎn)說(shuō)明。我們所有的聊天是邏輯都在目錄中的Events.php進(jìn)行修改。
下面我給大家貼一下我編寫(xiě)的部分份代碼。
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打開(kāi)(去掉//注釋),并執(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)客戶端斷開(kāi)連接時(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ì)開(kāi)發(fā)者透明
WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf";
// 開(kāi)啟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連接打開(kāi)時(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)買(mǎi)對(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>
上面是主要運(yùn)行的核心代碼。其他框架的自帶參數(shù)需要各位自己去根據(jù)文檔去調(diào)試優(yōu)化。到此基于workerman的聊天用于功能demo已經(jīng)搭建完畢。
本我是準(zhǔn)備接著寫(xiě)我那個(gè)多進(jìn)程教程的,今天心血來(lái)潮想看看swoole的websocket,
我就點(diǎn)開(kāi)了這個(gè)
WebSocket
我看了看官網(wǎng)的demo,覺(jué)得看起來(lái)很簡(jiǎn)單嘛,
<?php
//官網(wǎng)demo
$server=new swoole_websocket_server("0.0.0.0", 9501);
$server->on('open', function (swoole_websocket_server $server, $request) {
echo "server: handshake success with fd{$request->fd}\n";//$request->fd 是客戶端id
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
$server->push($frame->fd, "this is server");//$frame->fd 是客戶端id,$frame->data是客戶端發(fā)送的數(shù)據(jù)
//服務(wù)端向客戶端發(fā)送數(shù)據(jù)是用 $server->push( '客戶端id' , '內(nèi)容')
});
$server->on('close', function ($ser, $fd) {
echo "client {$fd} closed\n";
});
$server->start();
我就是喜歡這種簡(jiǎn)單易懂的demo ,每行代碼意思一看就明白
服務(wù)端有了,我找點(diǎn)客戶端的js代碼
火狐的MDN
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<script type="text/javascript">
var exampleSocket=new WebSocket("ws://0.0.0.0:9501");
exampleSocket.onopen=function (event) {
exampleSocket.send("親愛(ài)的服務(wù)器!我連上你啦!");
};
exampleSocket.onmessage=function (event) {
console.log(event.data);
}
</script>
</head>
<body>
<input type="text" id="content">
<button onclick="exampleSocket.send( document.getElementById('content').value )">發(fā)送</button>
</body>
</html>
最后命令行運(yùn)行php文件,之后瀏覽器打開(kāi)html文件,
F12打開(kāi)調(diào)試界面看console,ok , 沒(méi)有問(wèn)題
這個(gè)時(shí)候我突然想到一個(gè)事情,因?yàn)槲易龆噙M(jìn)程的那個(gè)教程里,在主進(jìn)程中會(huì)將所有的子進(jìn)程的句柄存起來(lái),以后進(jìn)行進(jìn)程間通訊用。
那么 我將所有的客戶端的鏈接存起來(lái)存成數(shù)組,每當(dāng)一個(gè)客戶端發(fā)送消息時(shí),我就遍歷這個(gè)客戶端數(shù)組,將消息群發(fā)一遍,不久實(shí)現(xiàn)了聊天室了嗎?
然后就,服務(wù)端代碼成了這個(gè)樣子
<?php
$map=array();//客戶端集合
$server=new swoole_websocket_server("0.0.0.0", 9501);
$server->on('open', function (swoole_websocket_server $server, $request) {
global $map;//客戶端集合
$map[$request->fd]=$request->fd;//首次連上時(shí)存起來(lái)
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
global $map;//客戶端集合
$data=$frame->data;
foreach($map as $fd){
$server->push($fd , $data);//循環(huán)廣播
}
});
$server->on('close', function ($ser, $fd) {
echo "client {$fd} closed\n";
});
$server->start();
哈哈 , 我覺(jué)得這樣就大功告成了,結(jié)果發(fā)現(xiàn)自己是 圖樣圖森破
大家可以自己試試,運(yùn)行php后 , 瀏覽器打開(kāi)兩個(gè)頁(yè)面,看看console.log的內(nèi)容是什么
運(yùn)行良好,可是并沒(méi)有實(shí)現(xiàn)我們說(shuō)的那種聊天效果。
找找原因吧。
我第一反映看看$map里面是什么,就輸出看看,結(jié)果發(fā)現(xiàn)這個(gè)map里面只有一個(gè)元素。
唉,不對(duì)啊,我這是全局變量,難道不應(yīng)該是有幾個(gè)客戶端鏈接,就有幾個(gè)元素嗎?
這是怎么回事啊,竟然沒(méi)有保存到所有客戶端id?
到了這一步,我解決不了map變量的這個(gè)問(wèn)題了,然后我就想看看那個(gè)fd是什么東西,
老規(guī)矩 var_dump輸出 , 發(fā)現(xiàn)fd就是 int類型的數(shù)字,并且是自增的
這好辦了,不就是數(shù)字嘛
于是呼,我就這樣做
變量存不了,我搞不定,我存文本里嘛。
最終版 websocket.php
<?php
$server=new swoole_websocket_server("0.0.0.0", 9501);
$server->on('open', function (swoole_websocket_server $server, $request) {
file_put_contents( __DIR__ .'/log.txt' , $request->fd);
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
global $client;
$data=$frame->data;
$m=file_get_contents( __DIR__ .'/log.txt');
for ($i=1 ; $i<=$m ; $i++) {
echo PHP_EOL . ' i is ' . $i . ' data is '.$data . ' m=' . $m;
$server->push($i, $data );
}
});
$server->on('close', function ($ser, $fd) {
echo "client {$fd} closed\n";
});
$server->start();
再次打開(kāi)html文件,多個(gè)頁(yè)面進(jìn)行輸入觀察,ok,可以了。
當(dāng)然,作為聊天室,我這寫(xiě)的也過(guò)于簡(jiǎn)陋了,界面大家自己可以寫(xiě)的好看一些(因?yàn)槲覒械膶?xiě)界面)
還有,每次的發(fā)送聊天的記錄,應(yīng)該存起來(lái),這樣,如果有新的連接連過(guò)來(lái)的時(shí)候,先把以前的聊天記錄發(fā)過(guò)去,這樣,我想體驗(yàn)更好一些
然后,大家可以愉快的聊天了。哈哈
在“疫情”期間已經(jīng)淘汰了一批末端的業(yè)務(wù)coder,現(xiàn)在是自己努力成為資深程序員的好時(shí)機(jī),才能在面對(duì)高薪職位邀請(qǐng)時(shí),做到胸有成竹。為了大家能夠順利進(jìn)階PHP中高級(jí)程序員、架構(gòu)師,我為大家準(zhǔn)備了一份中高級(jí)的教程福利!
作為web開(kāi)發(fā)的佼佼者PHP并不遜色其他語(yǔ)言,加上swoole后更加是如虎添翼!進(jìn)軍通信 、物聯(lián)網(wǎng)行業(yè)開(kāi)發(fā)百度地圖、百度訂單中心等!年后更是霸占程序員招聘語(yǔ)言第二名,疫情裁員期過(guò)后正是各大企業(yè)擴(kuò)大招人的時(shí)期,現(xiàn)在市場(chǎng)初級(jí)程序員泛濫,進(jìn)階中高級(jí)程序員絕對(duì)是各大企業(yè)急需的人才,這套教程適合那些1-6年的PHP開(kāi)發(fā)者進(jìn)階中高級(jí)提升自己,在春招中找到高薪職位!
*請(qǐng)認(rèn)真填寫(xiě)需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。