Added debugging capabilities
This commit is contained in:
parent
02715dd97f
commit
83a69b5049
2 changed files with 15 additions and 4 deletions
|
@ -6,10 +6,11 @@ import _thread
|
|||
|
||||
|
||||
class Server:
|
||||
def __init__(self, host_port_pair):
|
||||
def __init__(self, host_port_pair, debug=False):
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self.sock.bind(host_port_pair)
|
||||
self.sock.listen(2)
|
||||
self.debug = debug
|
||||
|
||||
|
||||
def run(self, handler, handler_args=[]):
|
||||
|
@ -23,11 +24,12 @@ class Server:
|
|||
self.sock.close()
|
||||
|
||||
def controller(self, sock, info, handler_args):
|
||||
sock = ESock(sock)
|
||||
sock = ESock(sock) if not self.debug else ESock(sock, debug=True)
|
||||
handler = self.handler(sock, info, **handler_args)
|
||||
while 1:
|
||||
try:
|
||||
handler.handle(*sock.recv())
|
||||
data, route = sock.recv()
|
||||
handler.handle(data, route)
|
||||
except (socket.error, OSError):
|
||||
handler.finish()
|
||||
handler.sock.close()
|
||||
|
|
|
@ -2,10 +2,13 @@ import json
|
|||
import socket
|
||||
import struct
|
||||
import DataTypes
|
||||
import Logging
|
||||
|
||||
class ESock:
|
||||
def __init__(self, sock):
|
||||
def __init__(self, sock, debug=False):
|
||||
self._sock = sock
|
||||
self.address, self.port = self._sock.getpeername()
|
||||
self.debug = debug
|
||||
|
||||
def __getattr__(self, attr):
|
||||
if attr == "recv":
|
||||
|
@ -40,10 +43,15 @@ class ESock:
|
|||
data = data.decode()
|
||||
elif data_type == DataTypes.json:
|
||||
data = json.loads(data.decode())
|
||||
if self.debug:
|
||||
Logging.info("Received %d-long '%s' on route '%s': %s (%s:%d)" % (data_length, type(data).__name__, route, str(data), self.address, self.port))
|
||||
return data, route
|
||||
|
||||
def send(self, data, route=""):
|
||||
length = len(data)
|
||||
data_type = type(data)
|
||||
if self.debug:
|
||||
Logging.info("Sending %d-long '%s' on route '%s': %s (%s:%d)" % (length, data_type.__name__, route, str(data), self.address, self.port))
|
||||
route = route.encode()
|
||||
if data_type is str:
|
||||
data = data.encode()
|
||||
|
@ -57,5 +65,6 @@ class ESock:
|
|||
self.sendall(struct.pack("cI16s", DataTypes.other, len(data), route) + data)
|
||||
|
||||
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.__dict == other.__dict__
|
Reference in a new issue