-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.py
95 lines (75 loc) · 2.66 KB
/
common.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
from __future__ import print_function
import socket, sys, re
class SocketUnexpectedClosed:
pass
class VerboseSocket:
def __init__(self, sock, name, print_func = print):
self.sock = sock
self.name = name
self.print_func = print_func
def recvfrom(self):
try:
data = self.sock.recvfrom(2048)
self.debug(repr(data), '<')
return data
except socket.error:
return (None, None)
def sendto(self, data, address):
self.sock.sendto(data, address)
self.debug(repr(address) + " -- " + repr(data), '>')
def send(self, arg):
self.sock.send(arg)
self.debug(repr(arg), '>')
def receive(self):
try:
data = self.sock.recv(2048)
if len(data) == 0:
raise SocketUnexpectedClosed()
except socket.error:
raise SocketUnexpectedClosed()
self.debug(repr(data), '<')
return data
def connect(self, target):
self.debug("Connecting to %s:%s" % target)
self.sock.connect(target)
self.debug("Connected!")
def bind(self, target):
self.sock.bind(target)
addr = self.sock.getsockname()
self.debug("Bound to %s:%s" % addr)
def close(self):
self.sock.close()
self.debug("Closed!")
def accept(self):
self.debug("Waiting for a client!")
client = self.sock.accept()
self.debug("A client connected! Remote is %s" % repr(client[1]))
return client
def listen(self, backlog = 1):
self.sock.listen(backlog)
self.debug("Listening, with a backlog of %s" % (backlog))
def fileno(self):
return self.sock.fileno()
def debug(self, message, style = ' '):
self.print_func("[%s%s] %s" % (style, self.name, message))
def getpeername(self):
return self.sock.getpeername()
class Communication(VerboseSocket):
def __init__(self, socket, name):
VerboseSocket.__init__(self, socket, name)
self.messages = []
def read_socket(self):
for line in self.receive().splitlines():
self.messages.insert(0, line)
def peek_socket(self):
(readvalid, _, _) = select.select([self], [], [], 0.01)
if self in readvalid:
self.read_socket()
def get_message(self):
while not self.messages:
self.read_socket()
return self.messages.pop()
def send_message(self, message):
self.send(message + "\n")
def null_print(message):
pass