• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            Fork me on GitHub
            隨筆 - 215  文章 - 13  trackbacks - 0
            <2017年6月>
            28293031123
            45678910
            11121314151617
            18192021222324
            2526272829301
            2345678


            專注即時通訊及網(wǎng)游服務(wù)端編程
            ------------------------------------
            Openresty 官方模塊
            Openresty 標(biāo)準(zhǔn)模塊(Opm)
            Openresty 三方模塊
            ------------------------------------
            本博收藏大部分文章為轉(zhuǎn)載,并在文章開頭給出了原文出處,如有再轉(zhuǎn),敬請保留相關(guān)信息,這是大家對原創(chuàng)作者勞動成果的自覺尊重!!如為您帶來不便,請于本博下留言,謝謝配合。

            常用鏈接

            留言簿(1)

            隨筆分類

            隨筆檔案

            相冊

            Awesome

            Blog

            Book

            GitHub

            Link

            搜索

            •  

            積分與排名

            • 積分 - 216872
            • 排名 - 118

            最新評論

            閱讀排行榜

            https://blog.csdn.net/orangleliu/article/details/50898014

            1 思路

            client的websocket連接到openresty之后,使用ngx.thread.spawn啟動兩個 輕線程,一個用來接收客戶端提交的數(shù)據(jù)往redis的channel寫,另一個用來訂閱channel,讀取redis的數(shù)據(jù)寫給客戶端。channel相當(dāng)于一個chat room,多個client一起訂閱,有人發(fā)聊天信息(pub),所有人都能得到信息(sub)。代碼比較簡陋,簡單的思路的實(shí)現(xiàn)。

            2 服務(wù)端代碼

            依賴:

            • openresty
            • redis
            • lua-resty-redis
            • lua-resty-websocket 只支持RFC 6455

            nginx的配置全貼了,就是兩個location,一個是頁面地址,一個是websocket地址。

            配置片段

                location = /sredis {
                    content_by_lua_file conf/lua/ws_redis.lua;
                }

                location ~ /ws/(.*) {
                    alias conf/html/$1.html;
                }
            • 1
            • 2
            • 3
            • 4
            • 5
            • 6
            • 7

            lua代碼

            -- simple chat with redis
            local server = require "resty.websocket.server"
            local redis = require "resty.redis"

            local channel_name = "chat"
            local msg_id = 0

            --create connection
            local wb, err = server:new{
              timeout = 10000,
              max_payload_len = 65535
            }

            --create success
            if not wb then
              ngx.log(ngx.ERR, "failed to new websocket: ", err)
              return ngx.exit(444)
            end


            local push = function()
                -- --create redis
                local red = redis:new()
                red:set_timeout(5000) -- 1 sec
                local ok, err = red:connect("127.0.0.1", 6379)
                if not ok then
                    ngx.log(ngx.ERR, "failed to connect redis: ", err)
                    wb:send_close()
                    return
                end

                --sub
                local res, err = red:subscribe(channel_name)
                if not res then
                    ngx.log(ngx.ERR, "failed to sub redis: ", err)
                    wb:send_close()
                    return
                end

                -- loop : read from redis
                while true do
                    local res, err = red:read_reply()
                    if res then
                        local item = res[3]
                        local bytes, err = wb:send_text(tostring(msg_id).." "..item)
                        if not bytes then
                            -- better error handling
                            ngx.log(ngx.ERR, "failed to send text: ", err)
                            return ngx.exit(444)
                        end
                        msg_id = msg_id + 1
                    end
                end
            end


            local co = ngx.thread.spawn(push)

            --main loop
            while true do
                -- 獲取數(shù)據(jù)
                local data, typ, err = wb:recv_frame()

                -- 如果連接損壞 退出
                if wb.fatal then
                    ngx.log(ngx.ERR, "failed to receive frame: ", err)
                    return ngx.exit(444)
                end

                if not data then
                    local bytes, err = wb:send_ping()
                    if not bytes then
                      ngx.log(ngx.ERR, "failed to send ping: ", err)
                      return ngx.exit(444)
                    end
                    ngx.log(ngx.ERR, "send ping: ", data)
                elseif typ == "close" then
                    break
                elseif typ == "ping" then
                    local bytes, err = wb:send_pong()
                    if not bytes then
                        ngx.log(ngx.ERR, "failed to send pong: ", err)
                        return ngx.exit(444)
                    end
                elseif typ == "pong" then
                    ngx.log(ngx.ERR, "client ponged")
                elseif typ == "text" then
                    --send to redis
                    local red2 = redis:new()
                    red2:set_timeout(1000) -- 1 sec
                    local ok, err = red2:connect("127.0.0.1", 6379)
                    if not ok then
                        ngx.log(ngx.ERR, "failed to connect redis: ", err)
                        break
                    end
                    local res, err = red2:publish(channel_name, data)
                    if not res then
                        ngx.log(ngx.ERR, "failed to publish redis: ", err)
                    end
                end
            end

            wb:send_close()
            ngx.thread.wait(co)


            3 頁面代碼

            <!DOCTYPE HTML>
            <html>

            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
                <script type="text/javascript">
                
            var ws = null;

                
            function WebSocketConn() {
                    
            if (ws != null && ws.readyState == 1) {
                        log(
            "已經(jīng)在線");
                        
            return
                    }

                    
            if ("WebSocket" in window) {
                        
            // Let us open a web socket
                        ws = new WebSocket("ws://localhost:8008/sredis");

                        ws.onopen 
            = function() {
                            log('成功進(jìn)入聊天室');
                        };

                        ws.onmessage 
            = function(event) {
                            log(event.data)
                        };

                        ws.onclose 
            = function() {
                            
            // websocket is closed.
                            log("已經(jīng)和服務(wù)器斷開");
                        };

                        ws.onerror 
            = function(event) {
                            console.log(
            "error " + event.data);
                        };
                    } 
            else {
                        
            // The browser doesn't support WebSocket
                        alert("WebSocket NOT supported by your Browser!");
                    }
                }

                
            function SendMsg() {
                    
            if (ws != null && ws.readyState == 1) {
                        
            var msg = document.getElementById('msgtext').value;
                        ws.send(msg);
                    } 
            else {
                        log('請先進(jìn)入聊天室');
                    }
                }

                
            function WebSocketClose() {
                    
            if (ws != null && ws.readyState == 1) {
                        ws.close();
                        log(
            "發(fā)送斷開服務(wù)器請求");
                    } 
            else {
                        log(
            "當(dāng)前沒有連接服務(wù)器")
                    }
                }

                
            function log(text) {
                    
            var li = document.createElement('li');
                    li.appendChild(document.createTextNode(text));
                    document.getElementById('log').appendChild(li);
                    
            return false;
                }
                
            </script>
            </head>

            <body>
                <div id="sse">
                    <href="javascript:WebSocketConn()">進(jìn)入聊天室</a> &nbsp;
                    <href="javascript:WebSocketClose()">離開聊天室</a>
                    <br>
                    <br>
                    <input id="msgtext" type="text">
                    <br>
                    <href="javascript:SendMsg()">發(fā)送信息</a>
                    <br>
                    <ol id="log"></ol>
                </div>
            </body>

            </html>

            4 效果

            用iphone試了試,不好使,可能是websocket版本實(shí)現(xiàn)的問題。pc端測試可以正常使用。

            這里寫圖片描述

            Reading

            posted on 2018-05-04 12:03 思月行云 閱讀(839) 評論(0)  編輯 收藏 引用 所屬分類: Nginx\Openresty
            午夜天堂av天堂久久久| 国产女人aaa级久久久级| 亚洲欧美伊人久久综合一区二区| 亚洲日本久久久午夜精品| 久久久无码精品亚洲日韩京东传媒| 久久午夜无码鲁丝片秋霞 | 久久99精品国产99久久6男男| 香蕉久久一区二区不卡无毒影院| 色婷婷久久久SWAG精品| 国产精品无码久久久久久| 亚洲国产婷婷香蕉久久久久久| 久久99国产精品久久99| 久久久精品人妻一区二区三区蜜桃 | 欧美综合天天夜夜久久| 亚洲精品国产字幕久久不卡| 久久久久亚洲AV成人网人人软件| 久久久亚洲欧洲日产国码aⅴ| 婷婷国产天堂久久综合五月| 51久久夜色精品国产| AV无码久久久久不卡网站下载| 日韩一区二区三区视频久久| 国产2021久久精品| 国产成人久久精品区一区二区| 亚洲精品乱码久久久久久中文字幕| 欧美性猛交xxxx免费看久久久| 色综合久久最新中文字幕| 日本人妻丰满熟妇久久久久久| 久久国产色av免费看| 久久久久波多野结衣高潮| 一本久久综合亚洲鲁鲁五月天亚洲欧美一区二区 | 久久久www免费人成精品| 久久久久亚洲AV无码专区桃色| 国产激情久久久久影院小草| 久久99精品国产一区二区三区| 99久久久国产精品免费无卡顿| 色欲久久久天天天综合网| 久久久久亚洲AV无码麻豆| 久久男人Av资源网站无码软件| 国产美女久久精品香蕉69| 日本久久久久久中文字幕| a级毛片无码兔费真人久久|