本文屬于入門級(jí)文章,大佬們可以繞過啦蔽介。如題摘投,本文會(huì)實(shí)現(xiàn)一個(gè)基于Swoole的websocket聊天室(可以群聊,也可以私聊虹蓄,具體還需要看數(shù)據(jù)結(jié)構(gòu)的設(shè)計(jì))犀呼。
搭建Swoole環(huán)境
通過包管理工具
# 安裝依賴包
$ sudo apt-get install libpcre3 libpcre3-dev
# 安裝swoole
$ pecl install swoole
# 添加extension拓展
$ echo extension=swoole.so > /etc/php5/cli/conf.d/swoole.ini
源碼編譯安裝
源碼安裝需要保證系統(tǒng)中有完善的工具包,如gcc薇组,然后就是固定的套路外臂。
./configure
sudo make
sudo make install
這里同樣不例外,大致步驟如下:
# 下載解壓源碼
wget https://github.com/swoole/swoole-src/archive/v1.9.1-stable.tar.gz
tar -xzvf v1.9.1-stable.tar.gz
cd swoole-src-1.9.1-stable
# 編譯安裝
phpize # phpize命令需要保證安裝了php7-dev,具體是php幾還是需要看自己安裝的PHP版本
./configure
sudo make
sudo make install
# 添加配置信息律胀,具體路徑按自己的情況而定
vi /etc/php/php.ini
// 在末尾加入宋光,路徑按make install生成的為準(zhǔn)
extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/swoole.so
上述兩種方式各有利弊貌矿,選擇合適自己的即可。
實(shí)現(xiàn)聊天室
在Swoole的wiki文檔中對(duì)此有很詳細(xì)的介紹罪佳,具體可以參考https://wiki.swoole.com/wiki/page/397.html 這里就不過多廢話了逛漫。下面主要聊聊我眼中的最簡單的聊天室的雛形:用戶可以選擇公聊或者私聊,然后服務(wù)器實(shí)現(xiàn)具體的業(yè)務(wù)邏輯赘艳。大致的數(shù)據(jù)結(jié)構(gòu)應(yīng)該是這個(gè)樣子的:
# 公聊結(jié)構(gòu)
{
"chattype":"publicchat",
"chatto":"0",
"chatmsg":"具體的聊天邏輯"
}
# 私聊結(jié)構(gòu)
{
"chattype":"privatechat",
"chatto":"2614677",
"chatmsg":"具體的聊天邏輯"
}
服務(wù)器端邏輯
因?yàn)橹皇茄菔咀谜保?wù)器端做的比較簡陋,大題分為兩部分:框架(server.php)+具體業(yè)務(wù)(dispatcher.php)
server.php
<?php
/**
* websocket服務(wù)器端程序
* */
//require "一個(gè)dispatcher蕾管,用來將處理轉(zhuǎn)發(fā)業(yè)務(wù)實(shí)現(xiàn)群組或者私聊";
require "/var/www/html/swoole/wschat/dispatcher.php";
$server = new swoole_websocket_server("0.0.0.0", 22223);
$server->on("open", function($server, $request) {
echo "client {$request->fd} connected, remote address: {$request->server['remote_addr']}:{$request->server['remote_port']}\n";
$welcomemsg = "Welcome {$request->fd} joined this chat room.";
// TODO 這里可以看出設(shè)計(jì)有問題枷踏,構(gòu)造方法里面應(yīng)該是通用的邏輯,而不是針對(duì)某一個(gè)方法有效
//$dispatcher = new Dispatcher("");
//$dispatcher->sendPublicChat($server, $welcomemsg);
foreach($server->connections as $key => $fd) {
$server->push($fd, $welcomemsg);
}
});
$server->on("message", function($server, $frame) {
$dispatcher = new Dispatcher($frame);
$chatdata = $dispatcher->parseChatData();
$isprivatechat = $dispatcher->isPrivateChat();
$fromid = $dispatcher->getSenderId();
if($isprivatechat) {
$toid = $dispatcher->getReceiverId();
$msg = "【{$fromid}】對(duì)【{$toid}】說:{$chatdata['chatmsg']}";
$dispatcher->sendPrivateChat($server, $toid, $msg);
}else{
$msg = "【{$fromid}】對(duì)大家說:{$chatdata['chatmsg']}";
$dispatcher->sendPublicChat($server, $msg);
}
/*
$chatmsg = json_decode($frame->data, true);
if($chatmsg['chattype'] == "publicchat") {
$usermsg = "Client {$frame->fd} 說:".$frame->data;
foreach($server->connections as $key => $fd) {
$server->push($fd, $usermsg);
}
}else if($chatmsg['chattype'] == "privatechat") {
$usermsg = "Client{$frame->fd} 對(duì) Client{$chatmsg['chatto']} 說: {$chatmsg['chatmsg']}.";
$server->push(intval($chatmsg['chatto']), $usermsg);
}
*/
});
$server->on("close", function($server, $fd) {
$goodbyemsg = "Client {$fd} leave this chat room.";
//$dispatcher = new Dispatcher("");
//$dispatcher->sendPublicChat($server, $goodbyemsg);
foreach($server->connections as $key => $clientfd) {
$server->push($clientfd, $goodbyemsg);
}
});
$server->start();
dispatcher.php
<?php
/**
* 用于實(shí)現(xiàn)公聊私聊的特定發(fā)送服務(wù)掰曾。
* */
class Dispatcher{
const CHAT_TYPE_PUBLIC = "publicchat";
const CHAT_TYPE_PRIVATE = "privatechat";
public function __construct($frame) {
$this->frame = $frame;
var_dump($this->frame);
$this->clientid = intval($this->frame->fd);
//$this->remote_addr = strval($this->frame->server['remote_addr']);
//$this->remote_port = intval($this->frame->server['remote_port']);
}
public function parseChatData() {
$framedata = $this->frame->data;
$ret = array(
"chattype" => self::CHAT_TYPE_PUBLIC,
"chatto" => 0,
"chatmsg" => "",
);
if($framedata) {
$ret = json_decode($framedata, true);
}
$this->chatdata = $ret;
return $ret;
}
public function getSenderId() {
return $this->clientid;
}
public function getReceiverId() {
return intval($this->chatdata['chatto']);
}
public function isPrivateChat() {
$chatdata = $this->parseChatData();
return $chatdata['chattype'] == self::CHAT_TYPE_PUBLIC ? false : true;
}
public function isPublicChat() {
return $this->chatdata['chattype'] == self::CHAT_TYPE_PRIVATE ? false : true;
}
public function sendPrivateChat($server, $toid, $msg) {
if(empty($msg)){
return;
}
foreach($server->connections as $key => $fd) {
if($toid == $fd || $this->clientid == $fd) {
$server->push($fd, $msg);
}
}
}
public function sendPublicChat($server, $msg) {
if(empty($msg)) {
return;
}
foreach($server->connections as $key => $fd) {
$server->push($fd, $msg);
}
}
}
客戶端
對(duì)websocket客戶端來說嚴(yán)格來講沒多大的限制旭蠕,通常我們會(huì)在移動(dòng)設(shè)備或者網(wǎng)頁上進(jìn)行客戶端的邏輯實(shí)現(xiàn)。這里拿網(wǎng)頁版的來簡單演示下:
wsclient.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>websocket client</title>
<style type="text/css">
.container {
border: #ccc solid 1px;
}
.up {
width: 100%;
height: 200px;
}
.down {
width: 100%;
height: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="up" id="chatrecord">
</div>
<hr>
<div class="down">
聊天類型:
<select id="chattype">
<option value="publicchat">公聊</option>
<option value="privatechat">私聊</option>
</select>
對(duì)
<select id="chatto">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
說:<input type="text" id="chatmsg" placeholder="隨便來一發(fā)吧~">
<input type="button" id="btnsend" value="發(fā)送" onclick="sendMsg()">
</div>
</div>
</body>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
var ws;
$(function(){
connect();
});
function echo(id, msg) {
console.log(msg);
$(id).append("<p>"+msg+"</p>");
}
function connect() {
ws = new WebSocket("ws://47.104.64.90:22223");
//ws.onopen = function(event) {echo("#chatrecord", event);}
//ws.onclose = function(event) {echo("#chatrecord", event);}
//ws.onerror = function(event) {echo("#chatrecord", event);}
ws.onmessage = function(event) {
echo("#chatrecord", event.data);
}
}
function sendMsg() {
var chatmsg = $("#chatmsg").val();
var chattype = $("#chattype").val();
var chatto = $("#chatto").val();
var msg = JSON.stringify({"chattype":chattype, "chatto":chatto, "chatmsg":chatmsg});
if(msg != "" && chatmsg !=""){
ws.send(msg);
$("#chatmsg").val("");
}
}
</script>
</html>
端口配置
由于阿里云端口的限制婴梧,這里nginx對(duì)外暴露的端口進(jìn)行了更改下梢。具體配置如下:
swoole.nginx.conf
server{
listen 22222;
server_name localhost;
index index.php;
root /var/www/html/swoole;
location / {
try_files $uri /index.php$is_args$args;
}
error_log /var/log/nginx/swoole_error.log;
access_log /var/log/nginx/swoole_access.log;
location ~ \.php$ {
root /var/www/html/swoole;
index index.php index.html index.htm;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
演示
演示之前,確保服務(wù)器端程序已經(jīng)開啟:
php server.php
運(yùn)行完命令之后塞蹭,沒有輸出就說明一切順利孽江。可以開啟客戶端進(jìn)行測試了番电。
-
部署測試
部署測試 -
公聊私聊測試
公聊私聊測試
總結(jié)
Swoole實(shí)現(xiàn)WebSocket服務(wù)岗屏,其實(shí)蠻清晰的。關(guān)鍵還是在于如何去設(shè)計(jì)漱办,有時(shí)候業(yè)務(wù)需求是一個(gè)不錯(cuò)的導(dǎo)向这刷,否則越到后面代碼會(huì)越臃腫,變得有“壞味道”娩井。相比上次使用Java的Netty框架實(shí)現(xiàn)的websocket聊天室(https://blog.csdn.net/marksinoberg/article/details/80337779)暇屋。這二者都屬于把業(yè)務(wù)邏輯從框架中剝開的實(shí)現(xiàn),所以開發(fā)者可以將更多地精力放到業(yè)務(wù)邏輯上來洞辣。從而開發(fā)出更健壯的服務(wù)咐刨。
最近寫的東西少的多了,不是因?yàn)閼械脤懷锼窃綄懺讲桓覍懥硕瘛C媾R大學(xué)畢業(yè),正式進(jìn)入社會(huì)了著瓶。很多東西不能再像之前一樣隨意联予,沒有什么深度。而深刻嚴(yán)謹(jǐn)?shù)闹R(shí)沒有時(shí)間的沉淀以及實(shí)踐的錘煉是學(xué)不來的。不是說看到了幾個(gè)名詞就學(xué)會(huì)了某項(xiàng)技術(shù)沸久,虛心向大佬們學(xué)習(xí)才是最切實(shí)的方法季眷。