-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.py
171 lines (142 loc) · 5.11 KB
/
helpers.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/python
""" helper functions, treat as header function to client and server """
import socket
import Queue
import threading
import time
import cPickle as pkl
import ujson
""" Eela IP 10.251.51.241
Matt IP 192.168.89.131
Sean IP 10.251.48.115
"""
class Stopwatch(object):
def __init__(self):
"""Initialize a new `Stopwatch`, but do not start timing."""
self.start_time = None
self.stop_time = None
def start(self):
"""Start timing."""
self.start_time = time.time()
def stop(self):
"""Stop timing."""
self.stop_time = time.time()
@property
def time_elapsed(self):
"""Return the number of seconds that have elapsed since this
`Stopwatch` started timing.
This is used for checking how much time has elapsed while the timer is
still running.
"""
assert not self.stop_time, \
"Can't check `time_elapsed` on an ended `Stopwatch`."
return time.time() - self.start_time
@property
def total_run_time(self):
"""Return the number of seconds that elapsed from when this `Stopwatch`
started to when it ended.
"""
return self.stop_time - self.start_time
def __enter__(self):
"""Start timing and return this `Stopwatch` instance."""
self.start()
return self
def __exit__(self, type, value, traceback):
"""Stop timing.
If there was an exception inside the `with` block, re-raise it.
>>> with Stopwatch() as stopwatch:
... raise Exception
Traceback (most recent call last):
...
Exception
"""
self.stop()
if type:
raise type, value, traceback
self.start()
return self
def __exit__(self, type, value, traceback):
"""Stop timing.
If there was an exception inside the `with` block, re-raise it.
>>> with Stopwatch() as stopwatch:
... raise Exception
Traceback (most recent call last):
...
Exception
"""
self.stop()
if type:
raise type, value, traceback
""" -assume data is of form: data = (seq_number, data_payload, prev_payloads)
-payloads is a list of all data payloads that are included,
in decr sequence order (e.g. [recent, ..., oldest])
-return tuple of: (new_current_seq, [most recent payload, ... oldest])
**** maybe reverse within this function itself???? see what works best """
def packet_handler(curr_seq_number, seq_number, payloads) :
# check if current sequence number matches the sent packet
if (curr_seq_number == seq_number) :
return (seq_number + 1, [payloads[0]])
# if this packet is no longer useful
elif (curr_seq_number > seq_number) :
return (curr_seq_number, [])
# we're behind, return as many packets we have that are useful
else :
del payloads[seq_number - curr_seq_number + 1:]
return (seq_number + 1, payloads)
#OR if del is funky: return (seq_number + 1, payloads[:seq_number - curr_seq_number + 1])
# see which is faster --> del may be better long run since modifies in place but idk
""" function that puts data, sequence, etc. in serialized string form
payloads should be a list of moves, most recent --> least """
def serializer(seq_num, payloads) :
# peanuts = {'seq_num': seq_num , 'payloads' : payloads}
peanuts = (seq_num, payloads)
return ujson.dumps(peanuts)
""" un-serializes objects in the packet, returns (seq_num, payloads)"""
def unserializer(UDP_data) :
return ujson.loads(UDP_data)
# peanuts = ujson.loads(UDP_data)
# return (peanuts['seq_num'], peanuts['payloads'])
""" listen on port UDP_PORTin, at ip UDP_IP for udp packets
that we then push to our queue q """
def listener(UDP_IP, UDP_PORTin, q,):
curr_seq = 0
#receiver: must bind to given listening address, will then listen for packets in loop later on
receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
receiver.bind((UDP_IP, UDP_PORTin))
# we listen for packets and send them to the game thread/ put them in the queue
while True:
data, addr = receiver.recvfrom(1024) # buffer size is 1024 bytes
q.put(data)
def server_listener(UDP_IP, UDP_PORTin, q,):
curr_seq = 0
#receiver: must bind to given listening address, will then listen for packets in loop later on
receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
receiver.bind((UDP_IP, UDP_PORTin))
# we listen for packets, but only queue moves that are relevant
while True:
data, addr = receiver.recvfrom(1024) # buffer size is 1024 bytes
seq_num, payloads = unserializer(data)
(curr_seq, moves) = packet_handler(curr_seq, seq_num, payloads)
# put moves on listening queue, oldest --> newest
for move in reversed(moves) :
q.put(move)
""" listens to a queue q, pulls a packet if queue is not empty and
sends it to FriendUDP_IP at port UDP_PORTout """
def sender(FriendUDP_IP, UDP_PORTout,q,b,):
sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
if q.qsize() > 0:#and count < 10:
packet = q.get()
sender.sendto(packet, (FriendUDP_IP, UDP_PORTout))
print 'sent' + b + '\n'
""" bs testing function by sean """
def packetcrafter(qi, qo):
## function that listens to a queue qi, pulls any pushed packets, crafts
## response packets and psuhes them to qo
while True:
if qi.qsize() > 0:
received = qi.get()
print 'received'
count = received[-1]
packet = str(time.time())+ "____" + str(int(count) + 1)
qo.put(packet)