python websocket 实时显示log

Posted on Posted in python
Tips: 本文创建于2016年5月30日,已超过 2 年,内容或图片可能已经失效!

## 前端

> html

  1. <body>  
  2. <head>    
  3. <meta http-equiv="content-type" content="text/html; charset=UTF-8">    
  4. <script src="socketclient.js"></script>    
  5. </head>   
  6. <script>  
  7. var client = new SocketClient("192.168.36.67",88,"chat");  
  8.    
  9. client.connect();  
  10.    
  11. client.onData  = function(text) {  
  12.     console.log(text);  
  13.     element=document.getElementById("log");  
  14.     if(element){  
  15.        if(element.value.length >100000) {  
  16.  element.value="";  
  17.  }  
  18.        element.value += (text + "\n");  
  19.        elementelement.scrollTop = element.scrollHeight;  
  20.     }  
  21. }  
  22.    
  23. client.onRegist = function() {  
  24.     this.sendData("I am coming!");  
  25. }  
  26.    
  27. </script>  
  28.    
  29. <textarea name="log" id="log" style="font-size:12px; width:100%; height: 600px;">Tcpdump log:</textarea>  
  30. </body>  
  31. </html>  

> js

  1. function SocketClient(ip,port,query) {    
  2.     var _this = this;    
  3.     this.socket = '';    
  4.     this.uid = 0;    
  5.     this.sign = '';    
  6.     this.connect = function() {    
  7.         this.socket = new WebSocket('ws://'+ip+':'+port+'/'+query);    
  8.         this.socket.onopen = function() {    
  9.             _this.onOpen()    
  10.         }    
  11.         this.socket.onmessage = function(event) {    
  12.             data = event.data;    
  13.             data = data.split("<split>")    
  14.             _this.uid = data[0];    
  15.             _this.sign = data[1];    
  16.             text = data[2];    
  17.                 
  18.             if(text!='SETUID') {      
  19.                 _this.onData(text);    
  20.             } else {    
  21.                 _this.onRegist()    
  22.             }    
  23.         }            
  24.         this.socket.onclose = function(event) {     
  25.             _this.onClose();    
  26.         };     
  27.     }    
  28.     this.onRegist = function() {    
  29.     
  30.     }    
  31.     this.onClose = function() {    
  32.     
  33.     }    
  34.     
  35.     this.onOpen = function() {    
  36.     
  37.     }    
  38.     
  39.     this.onData = function(text) {    
  40.     
  41.     }    
  42.         
  43.     this.sendData = function (text) {    
  44.         var data = this.uid+'<split>'+this.sign+'<split>'+text    
  45.         this.socket.send(data);    
  46.     }    
  47.         
  48.     this.close = function() {    
  49.         this.socket.close();    
  50.     }    
  51. }    

## 后端

[pywebsocketserver] [1]

[1]: https://github.com/suxianbaozi/pywebsocketserver

> log.py

  1. #! /usr/bin/env python    
  2. # -*- coding: utf-8 -*-    
  3.     
  4. import sys    
  5. import time     
  6. import threading    
  7. from pywebsocketserver.server import SocketServer    
  8. from pywebsocketserver.baseio import BaseIO    
  9. import subprocess    
  10.      
  11.      
  12. def tcpdump():      
  13.     global g_output_log    
  14.     popen=subprocess.Popen(['tail','-f',"/root/tmp/log"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)    
  15.     pid=popen.pid    
  16.     print('Popen.pid:'+str(pid))      
  17.     while True:      
  18.         line=popen.stdout.readline().strip()    
  19.         #line =popen.communicate()    
  20.         print "output:%s" %(line)    
  21.         g_output_log.append(line)    
  22.         if subprocess.Popen.poll(popen) is not None:      
  23.                 break    
  24.     print('DONE')      
  25.         
  26.      
  27. class MyIO(BaseIO):    
  28.     def onData(self,uid,text):    
  29.         self.sendData(uid,"received the message:%s"%(text,))    
  30.     def onConnect(self,uid):    
  31.         global g_uid    
  32.         g_uid=uid    
  33.         while True:    
  34.             #self.sendData(uid,"testing...")    
  35.             if  len(g_output_log) >0:    
  36.                 log = g_output_log.pop()    
  37.                 self.sendData(uid,log)    
  38.             else:    
  39.                 time.sleep(.01)    
  40.      
  41. try:    
  42.     g_output_log=[]    
  43.     g_uid=None    
  44.     tcpdump = threading.Thread(name='tcpdump', target=tcpdump)    
  45.     tcpdump.start()            
  46.     port = sys.argv[1]    
  47. except:    
  48.     port = 88    
  49.      
  50. port = int(port)    
  51. myIo = MyIO()    
  52. SocketServer(port,myIo).run()     

> pywebsocketserver/baseio.py

  1. # -*- coding: utf8 -*-  
  2.   
  3. class BaseIO:  
  4.     def __init__(self):  
  5.         return  
  6.     def onData(self,uid,text):  
  7.         '''请重写这个方法'''  
  8.         return  
  9.     def onConnect(self,uid):  
  10.         return  
  11.       
  12.     def sendData(self,uid,text):  
  13.         self.server.sendData(uid,text)  
  14.         '''发送数据'''  
  15.         return  
  16.     def onClose(self,uid):  
  17.         return  
  18.     def setServer(self,server):  
  19.         self.server = server  

> pywebsocketserver/server.py

  1. # -*- coding: utf8 -*-  
  2.   
  3. import socket  
  4. import time  
  5.   
  6.   
  7. from thread import SocketIoThread  
  8.   
  9.   
  10. class SocketServer:  
  11.     def __init__(self,port,IO):  
  12.         self.io = IO  
  13.         self.io.setServer(self)  
  14.         self.uid = 0  
  15.         self.port = port  
  16.         self.IoList = {}  
  17.     def run(self):  
  18.         sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)  
  19.         sock.bind(('',self.port))  
  20.         sock.listen(100)  
  21.   
  22.         while True:  
  23.             try:  
  24.                 connection,address = sock.accept()  
  25.                 self.uid += 1  
  26.                 self.IoList[self.uid] = SocketIoThread(connection,self.uid,self.io)  
  27.                 self.IoList[self.uid].start()  
  28.             except:  
  29.                 time.sleep(1)  
  30.               
  31.     def sendData(self,uid,text):  
  32.         if self.IoList.has_key(uid):  
  33.             print uid,text  
  34.             self.IoList[uid].sendData(text)  

> pywebsocketserver/thread.py

  1. # -*- coding: utf8 -*-  
  2.   
  3. import socket  
  4. import time  
  5. from threading import Thread  
  6. import hashlib  
  7. import base64  
  8. import struct  
  9. import json  
  10.   
  11. class SocketIoThread(Thread):  
  12.     def __init__(self,connection,uid,io):  
  13.         Thread.__init__(self)  
  14.         self.con = connection  
  15.         self.isHandleShake = False  
  16.         self.uid = uid  
  17.         self.io = io  
  18.         self.signKey = "ADS#@!D"  
  19.         self.online = True  
  20.     def run(self):  
  21.         while True:  
  22.             if not self.isHandleShake: #握手  
  23.                 try:  
  24.                     print "握手"  
  25.                     clientData  = self.con.recv(1024)  
  26.                     print clientData  
  27.                     dataList = clientData.split("\r\n")  
  28.                     header = {}  
  29.                     for data in dataList:  
  30.                         if ": " in data:  
  31.                             unit = data.split(": ")  
  32.                             header[unit[0]] = unit[1]  
  33.                     secKey = header['Sec-WebSocket-Key'];  
  34.                     resKey = base64.encodestring(hashlib.new("sha1",secKey+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest());  
  35.   
  36.                     response = '''HTTP/1.1 101 Switching Protocols\r\n'''  
  37.                     response += '''Upgrade: websocket\r\n'''  
  38.                     response += '''Connection: Upgrade\r\n'''  
  39.                     response += '''Sec-WebSocket-Accept: %s\r\n'''%(resKey,)  
  40.                     self.con.send(response)  
  41.                     self.isHandleShake = True  
  42.                     #返回用户id  
  43.                     self.sendData("SETUID")  
  44.                     self.io.onConnect(self.uid)  
  45.                     print "握手成功"  
  46.                 except:  
  47.                     return  
  48.             else:  
  49.                 try:  
  50.                     data_head = self.con.recv(1)  
  51.                     if repr(data_head)=='':  
  52.                         print "客户端断开链接"  
  53.                         self.onClose()  
  54.                         return  
  55.   
  56.                     header = struct.unpack("B",data_head)[0]  
  57.                     opcode = header & 0b00001111  
  58.                     print "操作符号%d"%(opcode,)  
  59.   
  60.                     if opcode==8:  
  61.                         print "客户端断开链接"  
  62.                         self.onClose()  
  63.                         return  
  64.   
  65.   
  66.                     data_length = self.con.recv(1)  
  67.                     data_lengths= struct.unpack("B",data_length)  
  68.                     data_length = data_lengths[0]& 0b01111111  
  69.                     masking = data_lengths[0] >> 7  
  70.                     if data_length<=125:  
  71.                         payloadLength = data_length  
  72.                     elif data_length==126:  
  73.                         payloadLength = struct.unpack("H",self.con.recv(2))[0]  
  74.                     elif data_length==127:  
  75.                         payloadLength = struct.unpack("Q",self.con.recv(8))[0]  
  76.                     print "字符串长度是:%d"%(data_length,)  
  77.                     if masking==1:  
  78.                         maskingKey = 
    ;self.con.recv(4)  
  79.                         self.maskingKey = maskingKey  
  80.                     data = self.con.recv(payloadLength)  
  81.                     if masking==1:  
  82.                         i = 0  
  83.                         true_data = ''  
  84.                         for d in data:  
  85.                             true_data += chr(ord(d) ^ ord(maskingKey[i%4]))  
  86.                             i += 1  
  87.                         self.onData(true_data)  
  88.                     else:  
  89.                         self.onData(data)  
  90.                 except Exception,e:  
  91.                     print e ,111  
  92.                     self.onClose()  
  93.                     return  
  94.     def onData(self,text) :  
  95.         try:  
  96.             uid,sign,value = text.split("<split>")  
  97.             uid = int(uid)  
  98.         except:  
  99.             print "数据格式不正确"  
  100.             self.con.close()  
  101.         hashStr = hashlib.new("md5",str(uid)+self.signKey).hexdigest()  
  102.         if hashStr!=sign:  
  103.             print "非法请求"  
  104.             self.con.close()  
  105.             return  
  106.         return self.io.onData(uid,value)  
  107.   
  108.     def onClose(self):  
  109.         self.con.close()  
  110.         self.online = False  
  111.         self.io.onClose(self.uid)  
  112.   
  113.     def packData(self,text):  
  114.   
  115.         sign = hashlib.new("md5",str(self.uid)+self.signKey).hexdigest()  
  116.         data = '%s<split>%s<split>%s'%(self.uid,sign,text)  
  117.         return data  
  118.  
       def sendData(self,text) :  
  119.   
  120.         text = self.packData(text)  
  121.         print text  
  122.         #头  
  123.         self.con.send(struct.pack("!B",0x81))  
  124.         #计算长度  
  125.         length = len(text)  
  126.        # masking = 0b00000000;  
  127.   
  128.         if length<=125:  
  129.             self.con.send(struct.pack("!B",length))  
  130.   
  131.         elif length<=65536:  
  132.             self.con.send(struct.pack("!B",126))  
  133.             self.con.send(struct.pack("!H",length))  
  134.         else:  
  135.             self.con.send(struct.pack("!B",127))  
  136.             self.con.send(struct.pack("!Q",length))  
  137.   
  138.         self.con.send(struct.pack("!%ds"%(length,),text))  
» 转载请注明来源:呢喃 » python websocket 实时显示log

Leave a Reply

Your email address will not be published. Required fields are marked *

eleven − 3 =