nginx,tornado,websocket,supervisord配置成型

简介: 因为要上生产环境,所以配置还是专业一些比较好。 nginx.conf upstream websocket_host { server 127.0.0.1:9527; } location /ws_log { proxy_redirect ...

因为要上生产环境,所以配置还是专业一些比较好。

nginx.conf

upstream websocket_host {
    server 127.0.0.1:9527;
}


location /ws_log {
            proxy_redirect    off;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $host;
            proxy_pass http://websocket_host;
        }
        location /websocket {
            proxy_redirect    off;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $host;
            proxy_pass http://websocket_host;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }

supervisord.conf

[program:tornado-9527]
command=python /X/X/websocket/ws.py
stdout_logfile=/var/log/tornado.log
stderr_logfile=/var/log/tornado.log
autostart=true
autorestart=true
startsecs=10
stopwaitsecs=600

wsapp.py

import tornado.ioloop
import tornado.web
import tornado.websocket
from tornado.ioloop import IOLoop
from datetime import timedelta
import time
import os
import sys
import tornado.httpserver


class WebSocketHandler(tornado.websocket.WebSocketHandler):
    file_content = ""
    filename = "test.log"

    def check_origin(self, origin):
        return True

    def open(self):
        pass

    def update_client(self):
        self.write_message(self._read_file(self.filename))

    def on_message(self, message):
        print message
        self.filename = message.split('-')[1]
        self.update_client()

    def on_close(self):
        pass

    def _read_file(self, filename):
        print filename, '================='
        with open("/tmp/"+filename) as f:
            content = f.read()
            content_diff = content.replace(self.file_content, '')
            self.file_content = content
            return content_diff


class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("websockets.html")


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/ws_log/', IndexPageHandler),
            (r'/websocket/ws', WebSocketHandler)
        ]
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            debug=True
        )
        tornado.web.Application.__init__(self, handlers, **settings)


if __name__ == '__main__':
    ws_app = Application()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(9527)
    tornado.ioloop.IOLoop.instance().start()

websocket.html

<link rel="stylesheet" href="/static/uikit-2.22.0/css/uikit.min.css" />
<link rel="stylesheet" href="/static/uikit-2.22.0/css/components/progress.gradient.css"/>
<link rel="stylesheet" href="/static/css/radialindicator.css"/>
<script src="/static/js/jquery-1.11.2.js"></script>
<script src="/static/js/radialIndicator.min.js"></script>
<script src="/static/uikit-2.22.0/js/uikit.js"></script>
<script src="/static/uikit-2.22.0/js/components/sticky.min.js"></script>



html
<div id="procPer"></div>
<br>
<textarea id="logoutput"  placeholder="日志输出" style="background:#000; color:#FFF; width:530;height:400" >...</textarea>
<br>
<a href="javascript:void(0);" onClick="wsFunc('stop', 'DEMO')"><span id="actionSpn"  class="uk-button">停止刷新</span></a>
<script>

function GetRequest() {
           var url = location.search;
           var theRequest = new Object();
           if (url.indexOf("?") != -1) {
                  var str = url.substr(1);
                  strs = str.split("&");
                  for(var i = 0; i < strs.length; i ++) {
                         theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
                  }
           }
           return theRequest;
        }
var Request = new Object();
Request = GetRequest();
console.log(Request);
var dev_version = Request['dev_version'];
console.log(dev_version);

wsFunc("refresh", dev_version);

function wsFunc(msg, dev_version) {
                var messageContainer = document.getElementById("logoutput");
                var percentContainer = document.getElementById("procPer");


                if ("WebSocket" in window) {
                        var ws = new WebSocket("ws://1.2.3.4/websocket/ws");
                        ws.onopen = function() {};
                        ws.onmessage = function (evt) {
                                messageContainer.innerHTML += evt.data;
                                var d = messageContainer.scrollHeight;
                                messageContainer.scrollTop = d;
                                var pattern = /progress/gi;
                                var ans = messageContainer.innerHTML.match(/\w+.\w+,\sdeploy\sprogress\s\d+/g);
                                var dic = new Array();
                                for (item in ans){
                                        dic_key = ans[item].split(',')[0];
                                        dic_value = ans[item].split(',')[1].split(" ")[3];
                                        dic[dic_key] = dic_value;
                                }
                                for (key in dic) {
                                        if(document.getElementById(key + "label") == undefined){
                                                var span=document.createElement('span');
                                                span.setAttribute("id", key + "label");
                                                percentContainer.appendChild(span);
                                                document.getElementById(key + "label").innerHTML = key
                                }
                                        if(document.getElementById(key) == undefined){
                                                var span=document.createElement('span');
                                                span.setAttribute("id", key);
                                                percentContainer.appendChild(span);
                                                //document.getElementById(key).innerHTML =dic[key];
                                                $(span).radialIndicator({
                                barColor: {
                                                                        10: '#0000FF',
                                                                        70: '#0000FF',
                                                                        90: '#0000FF',
                                                                        100: '#33CC33'
                                                                },
                                radius: 25,
                                barWidth: 3,
                                initValue: dic[key],
                                roundCorner : true,
                                percentage: true
                    });
                        radialObj =$(span).data('radialIndicator');

                                }
                                        radialObj.animate(dic[key]);

          
                    console.log(key, dic[key]);
                                }

                        };
                        ws.onclose = function() {};
                        console.log(msg);
                        if (msg == "refresh") {
                                sh=setInterval(function(){
                                ws.send(msg+"-"+dev_version, function(){})}
                                ,2000);

                        } else {
                                clearInterval(sh);
                                document.getElementById("actionSpn").innerText = 'OutPut';
                        }
                } else {
                        messageContainer.innerHTML += "此浏览器不支持websocket!";
                }
        }

</script>

 

目录
相关文章
|
1月前
|
缓存 应用服务中间件 网络安全
Nginx中配置HTTP2协议的方法
Nginx中配置HTTP2协议的方法
79 7
|
2月前
|
应用服务中间件 BI nginx
Nginx的location配置详解
【10月更文挑战第16天】Nginx的location配置详解
|
2月前
|
缓存 负载均衡 安全
Nginx常用基本配置总结:从入门到实战的全方位指南
Nginx常用基本配置总结:从入门到实战的全方位指南
325 0
|
2月前
|
应用服务中间件 Linux nginx
Jetson 环境安装(四):jetson nano配置ffmpeg和nginx(亲测)之编译错误汇总
这篇文章是关于在Jetson Nano上配置FFmpeg和Nginx时遇到的编译错误及其解决方案的汇总。
103 4
|
3天前
|
存储 应用服务中间件 nginx
nginx反向代理bucket目录配置
该配置实现通过Nginx代理访问阿里云OSS存储桶中的图片资源。当用户访问代理域名下的图片URL(如 `http://代理域名/123.png`)时,Nginx会将请求转发到指定的OSS存储桶地址,并重写路径为 `/prod/files/2024/12/12/123.png`。
31 5
|
27天前
|
缓存 负载均衡 算法
如何配置Nginx反向代理以实现负载均衡?
如何配置Nginx反向代理以实现负载均衡?
|
1月前
|
存储 负载均衡 中间件
Nginx反向代理配置详解,图文全面总结,建议收藏
Nginx 是大型架构必备中间件,也是大厂喜欢考察的内容,必知必会。本篇全面详解 Nginx 反向代理及配置,建议收藏。
Nginx反向代理配置详解,图文全面总结,建议收藏
|
19天前
|
负载均衡 前端开发 应用服务中间件
负载均衡指南:Nginx与HAProxy的配置与优化
负载均衡指南:Nginx与HAProxy的配置与优化
39 3
|
1月前
|
应用服务中间件 API nginx
nginx配置反向代理404问题
【10月更文挑战第18天】本文介绍了使用Nginx进行反向代理的配置方法,解决了404错误、跨域问题和302重定向问题。关键配置包括代理路径、请求头设置、跨域头添加以及端口转发设置。通过调整`proxy_set_header`和添加必要的HTTP头,实现了稳定的服务代理和跨域访问。
241 1
nginx配置反向代理404问题
|
27天前
|
负载均衡 监控 应用服务中间件
配置Nginx反向代理时如何指定后端服务器的权重?
配置Nginx反向代理时如何指定后端服务器的权重?
49 4