因为要上生产环境,所以配置还是专业一些比较好。
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>