在很早很早以前,WebSocket 協(xié)議還沒有被發(fā)明的時(shí)候,人們?cè)?Web 端制作類實(shí)時(shí)數(shù)據(jù)動(dòng)態(tài)更新時(shí),一般采用輪詢、 長(zhǎng)連接 (Long Polling) 來(lái)實(shí)現(xiàn)。大概就是:
輪詢:客戶端不停發(fā)送 HTTP 請(qǐng)求給服務(wù)端,服務(wù)端返回最新數(shù)據(jù)
長(zhǎng)連接:客戶端發(fā)送一條 HTTP 請(qǐng)求給服務(wù)端,服務(wù)端 HOLD 連接直到有新數(shù)據(jù)再返回
當(dāng)時(shí)的應(yīng)用有 WebQQ、FaceBook IM 等
但是這樣的實(shí)現(xiàn)有一個(gè)非常大的缺陷,HTTP 請(qǐng)求是半雙工 (Half Duplex) 的,只能由客戶端發(fā)送請(qǐng)求到服務(wù)端返回。大量的請(qǐng)求可能會(huì)導(dǎo)致 CPU 資源占用、內(nèi)存溢出等問題。于是 WebSocket 協(xié)議被發(fā)明了,與 HTTP 協(xié)議類似,地址為:ws:// (HTTP 頁(yè)面) 或 wss:// (HTTPS 頁(yè)面)。
WebSocket 是全雙工 (Full Duplex) 的,也就是說(shuō)服務(wù)端也可以發(fā)送數(shù)據(jù)到客戶端了。那比如在聊天時(shí),就可以省去客戶端的請(qǐng)求,對(duì)方客戶端有數(shù)據(jù)提交到服務(wù)端時(shí)直接由服務(wù)端發(fā)送至當(dāng)前客戶端。
比較知名的 WebSocket 框架有 http://Socket.io (node.js)、Workerman (PHP)、Swoole (PHP) 等 (我只嘗試過前兩個(gè))
Pokers 的群聊功能就是輪詢實(shí)現(xiàn)的,但是我的 1H1M1G 的小水管服務(wù)器是承受不住持續(xù)增長(zhǎng)的用戶量的,必須嘗試用 WebSocket 來(lái)實(shí)現(xiàn)了
<?php
//引入 composer
require '../vendor/autoload.php';
require_once '../vendor/workerman/workerman/Autoloader.php';
require_once '../vendor/workerman/channel/src/Server.php'; //Workerman 分組發(fā)送
require_once '../vendor/workerman/channel/src/Client.php'; //Workerman 分組發(fā)送
define('LAZER_DATA_PATH', dirname(dirname(__FILE__)) . '/data/'); //Pokers 使用的 json 數(shù)據(jù)庫(kù)
use Lazer\Classes\Database as Lazer;
use Workerman\Worker;
use Workerman\Lib\Timer;
$channel_server = new Channel\Server('0.0.0.0', 2206); //分組服務(wù)器地址
$worker = new Worker('websocket://0.0.0.0:2000'); //WebSocket 地址
$worker->count = 2; //Workerman 進(jìn)程數(shù)
// 全局群組到連接的映射數(shù)組
$group_con_map = array();
$worker->onWorkerStart = function ($worker) {
// Channel客戶端連接到Channel服務(wù)端
Channel\Client::connect('0.0.0.0', 2206);
// 監(jiān)聽全局分組發(fā)送消息事件
Channel\Client::on('send', function ($event_data) {
$thread = $event_data['thread_id'];
$con_id = $event_data['con_id'];
$mes_id = $event_data['mes_id'];
$speaker = $event_data['speaker'];
$class = $event_data['class_id'];
$array = Lazer::table('messages')->limit(1)->where('id', '=', (int) $mes_id)->andWhere('speaker', '=', (int) $speaker)->andWhere('belong_class', '=', (int) $class)->find()->asArray();
if (!!$array[0]['speaker']) {
global $group_con_map;
if (isset($group_con_map[$thread])) {
foreach ($group_con_map[$thread] as $con) {
$con->send(json_encode($array[0])); //發(fā)送數(shù)據(jù)到群組每位成員
}
}
} else {
$array = [
'op' => 'sent',
'status' => false,
'code' => 108,
'msg' => 'Illegal Request'
];
global $group_con_map;
$group_con_map[$thread][$con_id]->send(json_encode($array));
}
});
//心跳計(jì)時(shí)
Timer::add(55, function () use ($worker) {
foreach ($worker->connections as $connection) {
$array = [
'op' => 'keep'
];
$connection->send(json_encode($array));
}
});
};
//發(fā)送消息
$worker->onMessage = function ($con, $data) {
$data = json_decode($data, true);
$cmd = $data['action'];
$thread = $data['thread_id'];
$class = $data['class_id'];
$user = $data['speaker'];
$user_name = $data['speaker_name'];
@$mes_id = $data['mes_id'];
if (!empty($user_name) && !empty($thread) && !empty($class) && !empty($user)) {
$array = Lazer::table('classes')->limit(1)->where('id', '=', (int) $class)->find()->asArray();
if (!!$array) {
$array = Lazer::table('threads')->limit(1)->where('id', '=', (int) $thread)->andWhere('belong_class', '=', (int) $class)->find()->asArray();
if (!!$array) {
$array = Lazer::table('users')->limit(1)->where('id', '=', (int) $user)->andWhere('name', '=', (string) $user_name)->find()->asArray();
if (!!$array && in_array((string) $class, explode(',', $array[0]['class']))) { //判斷用戶存在
switch ($cmd) {
case "join": //客戶端加入群組
global $group_con_map;
// 將連接加入到對(duì)應(yīng)的群組數(shù)組里
$group_con_map[$thread][$con->id] = $con;
$array = [
'op' => 'join',
'thread' => $thread,
'status' => true,
'code' => 100
];
break;
case "send": //客戶端發(fā)送內(nèi)容
Channel\Client::publish('send', array(
'thread_id' => $thread,
'class_id' => $class,
'speaker' => $user,
'speaker_name' => $user_name,
'con_id' => $con->id,
'mes_id' => $mes_id
));
$array = [
'op' => 'send',
'status' => true,
'code' => 105
];
break;
default:
$array = [
'op' => 'send',
'status' => false,
'code' => 101,
'msg' => 'Illegal request'
];
break;
}
} else {
$array = [
'op' => 'send',
'status' => false,
'code' => 107,
'msg' => 'User does not exist or not in the class'
];
}
} else {
$array = [
'op' => 'send',
'status' => false,
'code' => 102,
'msg' => 'Thread does not exist'
];
}
} else {
$array = [
'op' => 'send',
'status' => false,
'code' => 103,
'msg' => 'Class does not exist'
];
}
} else {
$array = [
'op' => 'send',
'status' => false,
'code' => 104,
'msg' => 'Illegal request'
];
}
$con->send(json_encode($array));
};
// 這里很重要,連接關(guān)閉時(shí)把連接從全局群組數(shù)據(jù)中刪除,避免內(nèi)存泄漏
$worker->onClose = function ($con) {
global $group_con_map;
if (isset($con->group_id)) {
unset($group_con_map[$con->group_id][$con->id]);
if (empty($group_con_map[$con->group_id])) {
unset($group_con_map[$con->group_id]);
}
}
};
$worker->onConnect = function ($con) {
$array = [
'op' => 'connect',
'status' => true
];
$con->send(json_encode($array));
};
Worker::runAll();
前端js
//websocket 連接
this.ws = new WebSocket('wss://pokers.zeo.im/wss');
this.ws.onmessage = function (data) {
var re = eval('(' + data.data + ')');
switch (re.op) {
case 'send':
if (!re.status) {
antd.$message.error('Service Unavailable');
}
break;
case 'connect':
console.log('Connected to Pokers Server');
break;
case 'join':
if (!re.status) {
antd.$message.error('Service Unavailable');
}
break;
case 'keep':
break;
default:
//在內(nèi)容段后添加一段
antd.opened_mes_info.meses.push(re);
if (parseInt(re.speaker) !== parseInt(antd.user.id)) {
if ($(window).height() + $('#mes-container').scrollTop() >= $('#mes-inner').height()) {
//當(dāng)前窗口可視區(qū)域+滑動(dòng)距離大于總可滑動(dòng)高度,有更新直接到底部
antd.bottom_mes();
} else {
antd.unread.visible = true;
setTimeout(function () {
antd.unread.visible = false;
}, 1000);
}
}
antd.update_mes();
break;
}
};
JavaScript 連接代碼文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-707291.html
//廣播全 thread 在線用戶
this.ws.send('{"action":"send", "thread_id":' + antd.opened_mes_info.thread_id + ', "class_id":' + antd.opened_mes_info.class_id + ', "speaker":' + antd.user.id + ',"speaker_name":"' + antd.user.info.name + '","mes_id":' + res.data.code + '}');
JavaScript 發(fā)送代碼文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-707291.html
//加入當(dāng)前 Thread
this.ws.send('{"action":"join", "thread_id":' + id + ', "class_id":' + belong_class + ', "speaker":' + antd.user.id + ',"speaker_name":"' + antd.user.info.name + '"}');
到了這里,關(guān)于使用 PHP WorkerMan 構(gòu)建 WebSocket 全雙工群聊通信(二)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!