|
@@ -1,11 +1,11 @@
|
|
|
+#!/usr/bin/env python3
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
import json
|
|
|
import logging
|
|
|
import socket
|
|
|
-import random
|
|
|
+import uuid
|
|
|
from threading import Thread
|
|
|
-from datetime import datetime
|
|
|
|
|
|
# 广播端口
|
|
|
broadcast_port = 8888
|
|
@@ -25,37 +25,43 @@ def listen_broadcast():
|
|
|
data, address = s.recvfrom(2048)
|
|
|
# 接收到客户端广播消息
|
|
|
client_info = json.loads(data.decode('utf-8'))
|
|
|
- logging.info('broadcast msg: %s from %s' % (client_info, address[0]))
|
|
|
+ logging.info('broadcast from %s | %s' % (address[0], client_info))
|
|
|
|
|
|
# 将服务端配置信息发送给客户端
|
|
|
server_info = json.dumps({
|
|
|
'version': '0.1',
|
|
|
- 'id': '11111111',
|
|
|
+ 'id': str(uuid.uuid1()),
|
|
|
'manager_port': manager_port
|
|
|
})
|
|
|
- logging.info('send to %s, %s' % (address[0], server_info))
|
|
|
+ logging.info('send to %s | %s' % (address[0], server_info))
|
|
|
s.sendto(server_info.encode('utf-8'), address)
|
|
|
|
|
|
|
|
|
# 处理客户端消息
|
|
|
-def message_handle(client_conn, client_info):
|
|
|
+def message_handle(client_conn, client_address):
|
|
|
while True:
|
|
|
try:
|
|
|
msg_bytes = client_conn.recv(2048)
|
|
|
msg_str = msg_bytes.decode(encoding='utf8')
|
|
|
- logging.info('recv from %s, %s' % (client_info[0], str(msg_str)))
|
|
|
- # msg_json = json.loads(msg_str)
|
|
|
- str_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
|
|
- result = json.dumps({
|
|
|
- 'version': '0.1',
|
|
|
- 'id': '11111111',
|
|
|
- # 消息类型: msg, file, command
|
|
|
- 'type': 'command',
|
|
|
- 'value': 'echo 111 >> /tmp/run.log'
|
|
|
- })
|
|
|
+ logging.info('recv from %s | %s' % (client_address[0], str(msg_str)))
|
|
|
+ try:
|
|
|
+ # msg_json = json.loads(msg_str)
|
|
|
+ result = json.dumps({
|
|
|
+ 'version': '0.1',
|
|
|
+ 'id': str(uuid.uuid1()),
|
|
|
+ # 消息类型: msg, file, command
|
|
|
+ 'type': 'command',
|
|
|
+ 'value': 'echo 111 >> /tmp/run.log'
|
|
|
+ })
|
|
|
+ client_conn.send(result.encode('utf-8'))
|
|
|
+ except TypeError as te:
|
|
|
+ result = json.dumps({
|
|
|
+ 'msg': str(te)
|
|
|
+ })
|
|
|
+ logging.error(te)
|
|
|
client_conn.send(result.encode('utf-8'))
|
|
|
- except Exception as e:
|
|
|
- logging.warning('client %s offline, %s' % (client_info[0], e))
|
|
|
+ except ConnectionResetError as ce:
|
|
|
+ logging.error(ce)
|
|
|
break
|
|
|
|
|
|
|
|
@@ -92,8 +98,8 @@ if __name__ == '__main__':
|
|
|
|
|
|
while True:
|
|
|
# 为每个客户端启一个线程
|
|
|
- client, info = socket_server.accept()
|
|
|
- thread = Thread(target=message_handle, args=(client, info))
|
|
|
+ client, address = socket_server.accept()
|
|
|
+ thread = Thread(target=message_handle, args=(client, address))
|
|
|
thread.setDaemon(True)
|
|
|
thread.start()
|
|
|
except KeyboardInterrupt as ki:
|