1.1 --- a/gmyth-stream/server/plugins/comm/tcp.py Wed Apr 04 23:30:44 2007 +0100
1.2 +++ b/gmyth-stream/server/plugins/comm/tcp.py Tue Apr 17 21:13:22 2007 +0100
1.3 @@ -1,36 +1,79 @@
1.4 import lib
1.5 import time
1.6 import socket
1.7 +import logging as log
1.8
1.9 class Server(object):
1.10
1.11 def __init__(self, config):
1.12 - self.host = ''
1.13 + self.host = '0.0.0.0'
1.14 self.port = int(config.get("Comm", "port"))
1.15 self.finish = 0
1.16
1.17 + addr = (self.host, self.port)
1.18 + log.debug("Setup TCP server at %s:%s" % addr)
1.19 self.tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1.20 self.tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1.21 - self.tcp.bind( (self.host, self.port) )
1.22 + self.tcp.bind(addr)
1.23 self.tcp.listen(1)
1.24 + log.info("TCP server listening at %s:%s (sock=%d)" %
1.25 + (self.host, self.port, self.tcp.fileno()))
1.26
1.27 - def getMsg(self, size):
1.28 - return self.con.recv(size)
1.29 + def getMsg(self):
1.30 + bytes = []
1.31 + try:
1.32 + while 1:
1.33 + c = self.con.recv(1)
1.34 + bytes.append(c)
1.35 + if not c or c == "\n":
1.36 + break
1.37 + except Exception, e:
1.38 + log.error("Error reading message from client: %s" % e)
1.39 + return None
1.40 +
1.41 + if not bytes or bytes[-1] != "\n":
1.42 + msg = "".join(bytes)
1.43 + log.error("Invalid message from client: %r" % msg)
1.44 + return None
1.45 +
1.46 + # remove \n and \r
1.47 + bytes.pop()
1.48 + if bytes[-1] == "\r":
1.49 + bytes.pop()
1.50 +
1.51 + msg = "".join(bytes)
1.52 + log.debug("RECV: %r" % msg)
1.53 + return msg
1.54
1.55 def sendMsg(self, msg):
1.56 + log.debug("SEND: %r" % msg)
1.57 self.con.send(msg + "\n")
1.58
1.59 - def Ack(self, command):
1.60 - msg = "[%s] Command %s received" % (lib.now(), command)
1.61 - self.sendMsg(msg)
1.62 + def sendOk(self, payload=None):
1.63 + self.sendMsg("OK %d" % bool(payload is not None))
1.64 + if payload is not None:
1.65 + if not isinstance(payload, (tuple, list)):
1.66 + payload = (payload,)
1.67 + for e in payload:
1.68 + self.sendMsg("+%s" % e)
1.69 + self.sendMsg(".")
1.70 +
1.71 + def sendNotOk(self, reason=""):
1.72 + self.sendMsg("NOTOK %r" % reason)
1.73
1.74 def getRequest(self):
1.75 + log.debug("Wait for client request at %s:%s (sock=%d)" %
1.76 + (self.host, self.port, self.tcp.fileno()))
1.77 self.con, self.client = self.tcp.accept()
1.78 - print "[%s] Received request from ip=%s" % (lib.now(), self.client )
1.79 + log.info("Incoming request from %s (con=%s)" %
1.80 + (self.client, self.con.fileno()))
1.81 return (self.con, self.client, self.port)
1.82
1.83 def disconnect_client(self, connection):
1.84 + log.info("Closed request from %s (con=%s)" %
1.85 + (self.client, self.con.fileno()))
1.86 connection.close()
1.87
1.88 def stop(self):
1.89 + log.debug("Stop")
1.90 self.tcp.close()