1. 程式人生 > >Swoole實現基於WebSocket的群聊私聊

Swoole實現基於WebSocket的群聊私聊

                     

本文屬於入門級文章,大佬們可以繞過啦。如題,本文會實現一個基於Swoole的websocket聊天室(可以群聊,也可以私聊,具體還需要看資料結構的設計)。

搭建Swoole環境

通過包管理工具

# 安裝依賴包$ sudo apt-get install libpcre3 libpcre3-dev# 安裝swoole$ pecl install swoole# 新增extension拓展$ echo extension=swoole.so > /etc/php5/cli/conf.d/swoole.ini
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

原始碼編譯安裝

原始碼安裝需要保證系統中有完善的工具包,如gcc,然後就是固定的套路。

  • ./configure
  • sudo make
  • sudo make install

這裡同樣不例外,大致步驟如下:

# 下載解壓原始碼wget https://github.com/swoole/swoole-src/archive/v1.9.1-stable.tar.gztar -xzvf v1.9.1-stable.tar.gzcd swoole-src-1.9.1-stable# 編譯安裝phpize # phpize命令需要保證安裝了php7-dev,具體是php幾還是需要看自己安裝的PHP版本./configuresudo makesudo make install# 新增配置資訊,具體路徑按自己的情況而定vi /etc/php/php.ini
// 在末尾加入,路徑按make install生成的為準extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/swoole.so
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

上述兩種方式各有利弊,選擇合適自己的即可。

實現聊天室

在Swoole的wiki文件中對此有很詳細的介紹,具體可以參考https://wiki.swoole.com/wiki/page/397.html  這裡就不過多廢話了。下面主要聊聊我眼中的最簡單的聊天室的雛形:使用者可以選擇公聊或者私聊,然後伺服器實現具體的業務邏輯。大致的資料結構應該是這個樣子的:

 # 公聊結構 {     "chattype"
:"publicchat",     "chatto":"0",     "chatmsg":"具體的聊天邏輯" } # 私聊結構 {     "chattype":"privatechat",     "chatto":"2614677",     "chatmsg":"具體的聊天邏輯" }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

伺服器端邏輯

因為只是演示,伺服器端做的比較簡陋,大題分為兩部分:框架(server.php)+具體業務(dispatcher.php)

server.php

<?php/** * websocket伺服器端程式 * *///require "一個dispatcher,用來將處理轉發業務實現群組或者私聊";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 這裡可以看出設計有問題,構造方法裡面應該是通用的邏輯,而不是針對某一個方法有效    //$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}】對【{$toid}】說:{$chatdata['chatmsg']}";        $dispatcher->sendPrivateChat($server, $toid, $msg);     }else{        $msg = "【{$fromid}】對大家說:{$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} 對 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();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

dispatcher.php

<?php/** * 用於實現公聊私聊的特定傳送服務。 * */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);        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

客戶端

對websocket客戶端來說嚴格來講沒多大的限制,通常我們會在移動裝置或者網頁上進行客戶端的邏輯實現。這裡拿網頁版的來簡單演示下: 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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;            對            <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="隨便來一發吧~">            <input type="button" id="btnsend" value="傳送" 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

埠配置

由於阿里雲端口的限制,這裡nginx對外暴露的埠進行了更改。具體配置如下: 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;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

演示

演示之前,確保伺服器端程式已經開啟: php server.php 執行完命令之後,沒有輸出就說明一切順利。可以開啟客戶端進行測試了。

  • 部署測試 部署測試

  • 公聊私聊測試 公聊私聊測試

總結

Swoole實現WebSocket服務,其實蠻清晰的。關鍵還是在於如何去設計,有時候業務需求是一個不錯的導向,否則越到後面程式碼會越臃腫,變得有“壞味道”。相比上次使用Java的Netty框架實現的websocket聊天室(https://blog.csdn.net/marksinoberg/article/details/80337779)。這二者都屬於把業務邏輯從框架中剝開的實現,所以開發者可以將更多地精力放到業務邏輯上來。從而開發出更健壯的服務。

最近寫的東西少的多了,不是因為懶得寫,而是越寫越不敢寫了。面臨大學畢業,正式進入社會了。很多東西不能再像之前一樣隨意,沒有什麼深度。而深刻嚴謹的知識沒有時間的沉澱以及實踐的錘鍊是學不來的。不是說看到了幾個名詞就學會了某項技術,虛心向大佬們學習才是最切實的方法。