远程实时日志流传输
- 背景:线上维护有时需要实时观看日志流,但相关研发人员可能没线上权限,搭其它日志收集方案又过于重,人肉拉取效率低又浪费时间,于是想到这个方案。
server端代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name: server_recv_str.py
# Description:
# Author: handa
#
#-------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
import socket
server = socket.socket()
server.bind(('0.0.0.0', 38888)) # 将socket绑定到本机IP并且设定一个端口
server.listen(5) # 设置可以监听5个连接
exit = ''
while True:
con, addr = server.accept() # 会一直等待,直到连接客户端成功
print('连接到: ', addr)
while con:
msg = con.recv(1024).decode('utf-8','ignore') # 接受数据并按照utf-8解码
#msg = con.recv(1024).decode() # 接受数据并按照utf-8解码
#print('收到的数据是: ', msg)
#print('收到的数据类型是: ', type(msg))
print(msg)
sys.stdout.flush()
if msg == 'break':
con.close() # 关闭本次连接
exit = 'break'
break
if exit == 'break':
break
server.close() # 关闭服务器
client 端代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name: client_send_str
# Description:
# Author: handa
#
#-------------------------------------------------------------------------------
import socket
import sys
import sys
defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
reload(sys)
sys.setdefaultencoding(defaultencoding)
client = socket.socket()
client.connect(('172.16.6.159', 38888)) # 设置连接的服务器的IP和端口
line = sys.stdin.readline()
while True:
while line:
line = sys.stdin.readline()
print line
client.send(line.encode('utf-8')) # 设置编码为utf-8
#client.send(line.encode()) # 设置编码为utf-8
client.close()
改进的空间
https://stackoverflow.com/questions/23855604/implements-observer-pattern-on-socket-client-server
https://blog.csdn.net/weixin_34279184/article/details/86050684