-
Notifications
You must be signed in to change notification settings - Fork 1
/
task.py
executable file
·117 lines (94 loc) · 3.05 KB
/
task.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/usr/bin/env python3
# Author: Zhiwei Luo
from socket import *
import _pickle as pickle
import threading
class TaskLoader:
taskList = []
def __init__(self):
pass
def addTask(self, task):
self.taskList.append(task)
def getTaskCount(self):
return len(taskList)
def start(self):
for task in self.taskList:
task.run()
class Task:
strategy = None
def __init__(self, strategy):
self.strategy = strategy
def run(self):
if self.strategy != None:
while not self.strategy.checkFinished():
self.strategy.go()
class Strategy:
def checkFinished(self):
return True
def go(self):
pass
class NetworkInterface:
udpPort = 6666
socketUdp = None
isBufferFull = False
contextMouse = None
receiveBuffer = None
receiveAddr = None
broadcastAddr = None
myIPAddr = None
bufferList = []
threadReceive = None
def __init__(self, context=None, port=6666):
self.udpPort = port
self.contextMouse = context
def initSocket(self):
self.socketUdp = socket(AF_INET, SOCK_DGRAM)
self.myIPAddr = gethostbyname(gethostname())
network = self.myIPAddr.split('.')[0:3];network.append('255')
self.broadcastAddr = '.'.join(network)
self.socketUdp.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.socketUdp.bind(('', self.udpPort))
self.setBroadcastEnable()
def setBroadcastEnable(self):
self.socketUdp.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
def setBlocking(self, block):
self.socketUdp.setBlocking(block)
def setTimeout(self, seconds):
self.socketUdp.settimeout(seconds)
def receiveData(self):
#while not self.contextMouse.isEndNetwork:
try:
str, addr = self.socketUdp.recvfrom(1000)
self.bufferList.append((str, addr))
return (str, addr)
except Exception as e:
print('Receive Data Failed!')
raise e
def retrieveData(self):
if len(self.bufferList) > 0:
recvData = self.bufferList[0]
self.bufferList = self.bufferList[1:]
return pickle.loads(recvData)
else:
return None
def examineLatestData(self):
if len(self.bufferList) > 0:
recvData = self.bufferList[0]
return pickle.loads(recvData)
else:
return None
def receiveDataThread(self):
#while not self.contextMouse.isEndNetwork:
while True:
str, addr = self.socketUdp.recvfrom(1000)
self.bufferList.append(str)
def startReceiveThread(self):
self.threadReceive = threading.Thread(name='receive', target=self.receiveDataThread)
self.threadReceive.setDaemon(True)
self.threadReceive.start()
def sendStringData(self, str):
try:
self.socketUdp.sendto(pickle.dumps(str), (self.broadcastAddr, self.udpPort))
except Exception as e:
print('Send Data Failed!')
raise e