core.py
2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-02-07 13:59
# @Author : Lemon
# @File : core.py
# @Software: PyCharm
import functools
import json
from tornado import ioloop
from conf import settings
from core.monitor import Monitor
from lib import control_server
from lib.socket_ import MessageSocketClient
monitor = Monitor()
def server_replace(ws_url):
'''新开一个socket尝试连接新地址,存储在临时变量里'''
monitor._temp_socket = MessageSocketClient(connect_success, message_receive)
monitor._temp_socket.connect(ws_url, reconnect=False) # 失败不重试
def message_receive(message):
print("收到消息", message)
if message == 'login1':
monitor.login("[email protected]", "nantian888")
elif message == 'exit1':
monitor.logout('100047151842270')
else:
try:
req = json.loads(message)
type_ = req.get('type')
data_ = req.get('data')
if type_ == 'task':
commands = json.loads(data_)
for cmd in commands:
monitor.execute(cmd)
elif type_ == 'initialize':
monitor.init_config = json.loads(data_)
except:
import traceback
print(traceback.format_exc())
def host():
return 'ws://fbchat.data.gzntkj.com:8081', True
def connect_success(sock):
if monitor._temp_socket == sock:
sock.auto_reconnet = True # 新的连接成功后把断线重连开启
monitor._socket.quit() # 旧的断开
monitor._temp_socket = None # 清除临时变量
monitor.bind(sock) # 替换Sock
monitor.initialize() # 发送初始化消息
monitor._socket.new_server_func = functools.partial(
control_server.get_ws_address,
monitor._name,
sock.ws_url
) # 设置获取新服务器的函数
monitor._socket.server_replace = server_replace # 设置开启新服务器的逻辑
def run():
socket = MessageSocketClient(connect_success, message_receive)
socket.connect(**settings.get_server())
ioloop.IOLoop.instance().start()