`
haoningabc
  • 浏览: 1469893 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

nginx websocket的helloworld

阅读更多
https://github.com/openresty/lua-resty-websocket
的nginx的websocket的helloworld
先装openresty
配置文件为

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    charset utf-8,gbk;
    include       mime.types;
    default_type text/plain;

    lua_package_path "/data/www/lua/?.lua;;";

    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        lua_code_cache off;  
        location /lua_webc {   
          content_by_lua_file /data/www/lua/webs_client.lua;
        }  
        location /webs {   
          content_by_lua_file /data/www/lua/webs.lua;
        }  
        location / {
            root   html;
            index  index.html index.htm;
        }


        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

}

关键点是
        location /webs {   
          content_by_lua_file /data/www/lua/webs.lua;
        } 


websocket的lua代码为
[root@VM_192_107_centos lua]# cat webs.lua 
local server = require "resty.websocket.server"
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()

if not data then
    ngx.log(ngx.ERR, "failed to receive a frame: ", err)
    return ngx.exit(444)
end

if typ == "close" then
    -- send a close frame back:

    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
end

if typ == "ping" then
    -- send a pong frame back:

    local bytes, err = wb:send_pong(data)
    if not bytes then
        ngx.log(ngx.ERR, "failed to send frame: ", err)
        return
    end
elseif typ == "pong" then
    -- just discard the incoming pong frame

else
    ngx.log(ngx.INFO, "received a frame of type ", typ, " and payload ", data)
end

wb:set_timeout(1000)  -- change the network timeout to 1 second

bytes, err = wb:send_text("Hello world")
if not bytes then
    ngx.log(ngx.ERR, "failed to send a text frame: ", err)
    return ngx.exit(444)
end

bytes, err = wb:send_binary("blah blah blah...")
if not bytes then
    ngx.log(ngx.ERR, "failed to send a binary frame: ", err)
    return ngx.exit(444)
end

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
[root@VM_192_107_centos lua]# 

客户端html代码
<html>
<head>
<script>
var ws = null;
function connect() {
  if (ws !== null) return log('already connected');
  ws = new WebSocket('ws://haoning.net/webs');
  ws.onopen = function () {
    log('connected');
  };
  ws.onerror = function (error) {
    log(error);
  };
  ws.onmessage = function (e) {
    log('recv: ' + e.data);
  };
  ws.onclose = function () {
    log('disconnected');
    ws = null;
  };
  return false;
}
function disconnect() {
  if (ws === null) return log('already disconnected');
  ws.close();
  return false;
}
function send() {
  if (ws === null) return log('please connect first');
  var text = document.getElementById('text').value;
  document.getElementById('text').value = "";
  log('send: ' + text);
  ws.send(text);
  return false;
}
function 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();">
      Connect
    </button>
    <button type="button" onclick="return disconnect();">
      Disconnect
    </button>
    <input id="text" type="text">
    <button type="submit">Send</button>
  </form>
  <ol id="log"></ol>
</body>
</html>
分享到:
评论

相关推荐

    Golang 搭建 Web 聊天室

    4. **项目实践**:教程涵盖了从简单的 "Hello World" 程序到逐步构建聊天室的全过程。在项目部分,可能会讲解如何创建服务器端接收和广播消息,以及客户端如何连接、发送和接收消息的逻辑。 5. **技术扩展**:...

    使用Nginx_Supervisor_tornado搭建web服务.pdf

    这个应用将监听8000端口,并在访问根URL时返回"Hello, world!"。 **3.2. Supervisor配置** 在Supervisor的配置文件中,为你的Tornado应用添加一个配置段,如下: ``` [program:your_app_name] command=/usr/bin/...

    uwsgi+nginx部署Django项目操作示例

    return [b"Hello World"] # 运行uWSGI服务 uwsgi --http :9090 --wsgi-file test.py ``` 通过浏览器访问`http://localhost:9090`,如果看到“Hello World”的页面,则说明安装及配置成功。 #### 创建Django项目 ...

    Ruby-agoo一个用于Ruby的高性能HTTP服务器

    server.add '/hello', -&gt;(req, res) { res.text = 'Hello, World!' } server.start ``` 3. 部署:在生产环境中,agoo可以与反向代理如Nginx配合使用,以更好地管理负载和提供静态文件服务。 四、性能对比 与其他...

    基于Flask的简单Web应用

    这个函数将返回"Hello, World!"文本作为响应。 6. **运行服务器** 使用`app.run()`命令启动开发服务器。在命令行中运行`python app.py`,然后在浏览器中访问`http://localhost:5000`,就可以看到你的Web应用了。 ...

    node-course

    了解Node.js的安装、环境配置以及Hello World程序,是开始Node.js之旅的第一步。 三、Node.js核心模块 1. 文件系统(fs):Node.js提供了一个内置的fs模块,用于处理文件和目录操作,如读取、写入、创建和删除文件...

    flask

    在这个例子中,访问根URL("/")时,会触发`hello_world`函数,返回"Hello, World!"的响应。 Flask的核心组件包括: 1. **请求对象** (Request):用于获取HTTP请求的信息,如参数、头信息、数据等。 2. **响应对象...

    flask-tutorial

    例如,上述代码中,根路径'/'将调用hello_world()函数。 5. 模板渲染与Jinja2 Flask使用Jinja2模板引擎处理HTML模板。在templates目录下创建一个index.html文件,然后在视图函数中返回渲染后的模板: ```python ...

    nodeJs开发文档

    文档可能介绍了如何安装Node.js,创建第一个“Hello, World!”程序,以及Node.js的全局对象和基本数据类型。 2. **模块系统**:Node.js采用CommonJS模块规范,每个文件都是一个模块,有自己的作用域。`require`函数...

    [Mastering.Node.js(2013.11) 精通Node.js

    学习node.js的好书 下面是目录: Preface 1 ...Hello World 309 Creating a calculator 311Table of Contents [ vii ] Implementing callbacks 313 Closing thoughts 314 Links and resources 315 Index 317

    express_example

    例如,`app.get('/hello', function(req, res) { res.send('Hello World!'); })`将处理所有GET请求到'/hello'的请求。 3. **模板引擎**:Express支持多种模板引擎,如ejs、jade(现在称为pug)、handlebars等,用于...

    tornado-quick-setup:在进行一些配置之后,按照自述文件,基于龙卷风的Web服务将运行

    self.write("Hello, world") def make_app(): return tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": parse_command_line() app = make_app() app.listen(options.port) ...

    nodejs_training

    - **Hello, World**:通过创建第一个 "Hello, World" 应用,学习基本的文件结构和 `console.log()` 函数的使用。 - **模块系统**:理解 CommonJS 模块规范,以及 `require` 和 `module.exports` 的工作原理。 2. ...

    fast-api-study

    例如,创建一个返回"Hello, World!"的简单路由: ```python from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello, World!"} ``` 四、处理请求参数 FastAPI...

Global site tag (gtag.js) - Google Analytics