renatofilho@484: import lib renatofilho@484: import time renatofilho@484: import socket morphbr@511: import logging as log renatofilho@484: morphbr@499: class Server(object): renatofilho@484: renatofilho@484: def __init__(self, config): morphbr@511: self.host = '0.0.0.0' renatofilho@484: self.port = int(config.get("Comm", "port")) renatofilho@484: self.finish = 0 renatofilho@484: morphbr@511: addr = (self.host, self.port) morphbr@511: log.debug("Setup TCP server at %s:%s" % addr) renatofilho@484: self.tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) renatofilho@484: self.tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) morphbr@511: self.tcp.bind(addr) renatofilho@484: self.tcp.listen(1) morphbr@511: log.info("TCP server listening at %s:%s (sock=%d)" % morphbr@511: (self.host, self.port, self.tcp.fileno())) renatofilho@484: morphbr@511: def getMsg(self): morphbr@511: bytes = [] morphbr@511: try: morphbr@511: while 1: morphbr@511: c = self.con.recv(1) morphbr@511: bytes.append(c) morphbr@511: if not c or c == "\n": morphbr@511: break morphbr@511: except Exception, e: morphbr@511: log.error("Error reading message from client: %s" % e) morphbr@511: return None morphbr@511: morphbr@511: if not bytes or bytes[-1] != "\n": morphbr@511: msg = "".join(bytes) morphbr@511: log.error("Invalid message from client: %r" % msg) morphbr@511: return None morphbr@511: morphbr@511: # remove \n and \r morphbr@511: bytes.pop() morphbr@511: if bytes[-1] == "\r": morphbr@511: bytes.pop() morphbr@511: morphbr@511: msg = "".join(bytes) morphbr@511: log.debug("RECV: %r" % msg) morphbr@511: return msg renatofilho@484: renatofilho@484: def sendMsg(self, msg): morphbr@511: log.debug("SEND: %r" % msg) renatofilho@484: self.con.send(msg + "\n") renatofilho@484: morphbr@511: def sendOk(self, payload=None): morphbr@511: self.sendMsg("OK %d" % bool(payload is not None)) morphbr@511: if payload is not None: morphbr@511: if not isinstance(payload, (tuple, list)): morphbr@511: payload = (payload,) morphbr@511: for e in payload: morphbr@511: self.sendMsg("+%s" % e) morphbr@511: self.sendMsg(".") morphbr@511: morphbr@511: def sendNotOk(self, reason=""): morphbr@511: self.sendMsg("NOTOK %r" % reason) renatofilho@484: renatofilho@484: def getRequest(self): morphbr@511: log.debug("Wait for client request at %s:%s (sock=%d)" % morphbr@511: (self.host, self.port, self.tcp.fileno())) renatofilho@484: self.con, self.client = self.tcp.accept() morphbr@511: log.info("Incoming request from %s (con=%s)" % morphbr@511: (self.client, self.con.fileno())) morphbr@504: return (self.con, self.client, self.port) renatofilho@484: renatofilho@484: def disconnect_client(self, connection): morphbr@511: log.info("Closed request from %s (con=%s)" % morphbr@511: (self.client, self.con.fileno())) renatofilho@484: connection.close() renatofilho@484: renatofilho@484: def stop(self): morphbr@511: log.debug("Stop") renatofilho@484: self.tcp.close()