socket传数据并记录到文件中
最近在新项目中要通过socket传一些数据,下面是程序:
功能:
- 将客户端发送的json数据写入到日志文件中,如果数据不是json的,丢弃。
程序如下:
#!/usr/bin/env python # coding=utf-8 import SocketServer import datetime import json class MyServer(SocketServer.BaseRequestHandler): def handle(self): while True: data = self.request.recv(4096) if len(data) == 0: break if self.is_json(data) and not data.isdigit(): with open('/tmp/ip.log', 'a') as f: tm = self.nowtime() f.write(tm + data.decode() + '\n') def nowtime(self): return datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S] ') def is_json(self, data): try: json.loads(data) except ValueError as e: return False return True if __name__ == '__main__': server = SocketServer.ThreadingTCPServer(('0.0.0.0', 2985), MyServer) server.serve_forever()