码迷,mamicode.com
首页 > 其他好文 > 详细

lua socket案例

时间:2015-11-15 19:04:14      阅读:464      评论:0      收藏:0      [点我收藏+]

标签:

安装就不说了,上篇有写

location /chat/sub {
    #ngx.header.content_type = "text/html";
     default_type ‘text/html‘;
     content_by_lua_file /data/www/lua/sub.lua;
}

location /chat/pub {
   default_type ‘text/html‘;
   content_by_lua_file /data/www/lua/pub.lua;
}

 

vi  /data/www/lua/sub.lua;文件如下

    local num = 0;
    local maxNum = 600;
    local server = require "resty.websocket.server"
    local key = name; 
   local wb, err = server:new{
          timeout = 5000,  -- in milliseconds
          max_payload_len = 65535,
    }

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


    local data, typ, err = wb:recv_frame()  --data是客户端传过来的数据

    --[[  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() --服务端主动发送ping动作
        if not bytes then
          ngx.log(ngx.ERR, "failed to send ping: ", err)  --ping返回失败
          return ngx.exit(444)
        end 
      elseif typ == "close" then  --客户端传过来close动作请求
                local bytes, err = wb:send_close(1000, "enough, enough!")
                if not bytes then
                ngx.log(ngx.ERR, "failed to send the close frame: ", err)
                return
                end
                local code = err
                ngx.log(ngx.INFO, "closing with status code ", code, " and message ", data)
                return   
      elseif typ == "ping" then  --客户端传过来ping动作请求
        local bytes, err = wb:send_pong() --服务端响应对方的ping动作
        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.INFO, "client ponged") 
          else
                 ngx.log(ngx.INFO, "received a frame of type ", typ, " and payload ", data)
          end
                          
          
        wb:set_timeout(5000)  -- 设置网络超时

        while num < maxNum do  --每次长连接最多保持30秒   
                    local channels = ngx.shared.channels;
                    local value = channels:get("name"); 
                        local bytes, err = wb:send_text(value) 
                        if not bytes then 
                          ngx.log(ngx.ERR, "failed to send text: ", err) 
                          return ngx.exit(444) 
                        end    
                         num = num + 1;                  
                ngx.sleep(0.5);
        end  --while结束

    wb:send_close(); 

 

vi  /data/www/lua/pub.lua;文件如下

 local args = ngx.req.get_uri_args();
    local act = args[act];
    local msg = args[msg];
    if act == nil then
        act = "chat";
    end


function set_to_cache(key, value, exptime)
        if not exptime then
                exptime = 0
        end
        local channels = ngx.shared.channels
        local succ, err, forcible = channels:set(key, value, exptime)
        return succ
end
 
function get_from_redis(key)
                local redis = require "resty.redis"
                local red = redis:new()

        red:set_timeout(1000) 
        local ok, err = red:connect("127.0.0.1", 6379)
        if not ok then
                ngx.say("failed to connect: ", err)
                return
        end

        local res, err = red:get(key)
        if not res then
               red:set(key, msg);
               --ngx.say("failed to get doy: ", err)
               -- return ngx.null
        end
          
        set_to_cache(key, msg)
        ngx.say("这次是从reids取的.")
        return msg
end

function get_from_cache(key, msg)
      if msg == nil then
         local channels = ngx.shared.channels;
         local value = channels:get(key)
         if not value then
                value = get_from_redis(key)
                set_to_cache(key, value)
                return value
         end
         
         ngx.say("这次是从nginx缓存取的.")
         return value;
       end
       ngx.say(新设置的值);
      set_to_cache(key, msg);
       return msg;
end
local rs = get_from_cache(act ,msg)
ngx.say(rs)

 

 

 

 

前端代码如下:

[root@localhost lua]# vi /data/www/kohana/application/views/website/fr.php 

<html>
<head>
<script>
var ws = null;
function connect() {
        if (ws !== null) return log(already connected);
            ws = new WebSocket(ws://192.168.137.222/chat/sub);
            ws.onopen = function () {
                        log(哈哈连接上了);
            };

                ws.onerror = function (error) {
                        log(error);
                };

                ws.onmessage = function (e) {
                    log(消息推送过来了:  + e.data);
                };

                ws.onclose = function () {
                log(断开连接);
                    ws = null;
                };
           return false;
}

function disconnect() {
        if (ws === null) return log(断开连接);
        ws.close();
        return false;
}

function send() {
        if (ws === null) return log(还没有连接);
        var text = document.getElementById(text).value;
        document.getElementById(text).value = "";
        log(send:  + text);
        ws.send(text);
        return false;
}

function log(text) {
      console.log(text);
        var li = document.createElement(li);
        li.appendChild(document.createTextNode(text));
        document.getElementById(log).appendChild(li);
        return false;
}
</script>
</head>
<body>
<form onsubmit="return send();">
        <button type="button" onclick="return connect();">连接</button>
        <button type="button" onclick="return disconnect();">断开</button>
        <input id="text" type="text">
        <button type="submit">发送</button>
</form>
<ol id="log"></ol>
</body>
</html>

 

lua socket案例

标签:

原文地址:http://www.cnblogs.com/sixiong/p/4966984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!