-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathSocketThread.py
97 lines (81 loc) · 2.5 KB
/
SocketThread.py
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import socket
import threading
import time
import inspect
import ctypes
from json import *
class SocketThread(threading.Thread):
def __init__(self, myAddress, remoteAddress):
print('init socket')
# import traceback
# traceback.print_stack()
threading.Thread.__init__(self)
self.myAddress = myAddress
self.remoteAddress = remoteAddress
self.socketObj = None
self.windowID = 1
def isListening(self):
return self.socketObj is not None
def run(self):
print('run', self.name)
address = self.myAddress
self.socketObj = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socketObj.bind(address)
while True:
data, addr = self.socketObj.recvfrom(1024 * 5)
dataStr = data.decode()
dataObj = JSONDecoder().decode(dataStr)
funName = dataObj.get('f')
paramDict = dataObj.get('p')
print('recv:', funName, paramDict)
funObj = getattr(self, funName)
if funObj:
funObj(paramDict)
print ('close socket')
self.socketObj.close()
def stop(self):
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
print('terminate connection thread')
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
# 强行结束进程
_async_raise(self.ident, SystemExit)
# 关闭socket
self.socketObj.close()
self.socketObj = None
def send(self, data):
if self.socketObj:
self.socketObj.sendto(data.encode(), self.remoteAddress)
def remoteCall(self, funName, paramDict):
codeDic = {'f':funName, 'p':paramDict}
codeStr = JSONEncoder().encode(codeDic)
self.send(codeStr)
def goToPage(self, param):
print('go to page', param)
import sublime
window = sublime.active_window()
for win in sublime.windows():
if win.id() == self.windowID:
window = win
if window:
window.open_file('%s:%s:%s'% (param[0], param[1], param[2]+1), sublime.ENCODED_POSITION)
if __name__ == "__main__":
add1 = ('127.0.0.1', 12345)
add2 = ('127.0.0.1', 12346)
t1 = SocketThread(add1, add2)
t2 = SocketThread(add2, add1)
t1.start()
t2.start()
time.sleep(1)
#t1.send('1 -> 2')
#t2.send('2 -> 1')
t1.remoteCall('fun',{'p1':1})