Beispiel #1
0
 def __init__(self, host, port, ed):
     self.host = (host, port)
     self.readingError = self.writingError = False
     self.msg = NetworkMessage()
     self.ed = ed
     self.netview = NetworkView(self, self.ed)
     self.netcontrol = NetworkController(self.ed)
     self.connectionLock = thread.allocate_lock()
     self.ssl = None
Beispiel #2
0
class Connection:

    def __init__(self, host, port, ed):
        self.host = (host, port)
        self.readingError = self.writingError = False
        self.msg = NetworkMessage()
        self.ed = ed
        self.netview = NetworkView(self, self.ed)
        self.netcontrol = NetworkController(self.ed)
        self.connectionLock = thread.allocate_lock()
        self.ssl = None
        
    def connect(self, use_ssl=False):
        #print self.host
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if use_ssl:
            self.ssl = ssl.wrap_socket(self.socket, ssl_version=ssl.PROTOCOL_SSLv23)
            self.ssl.connect(self.host)
        else:
            self.socket.connect(self.host)
        thread.start_new_thread(self.parse_packet, ())
        #self.ed.post(ConnectedEvent())
        ConnectedEvent().post(self.ed)
        return

    def check_state(self):
        if self.writingError is True or self.readingError is True:
            self.close_connection()
            return False
        return True

    def parse_packet(self):
        while self.check_state():
            self.msg.buffer = self.safe_recv(2048)  #ACQUIRE PACKET BRO
            if isinstance(self.msg.buffer, basestring) and self.msg.buffer != "":
                self.netcontrol.on_recv_message(self.msg)
            self.msg.reset()
        return
        
    def send(self, msg): # Can be called from any thread
        if not self.check_state():
            return
        self.connectionLock.acquire()
        self.netview.on_send_message(msg)
        self.internal_send(msg)
        self.connectionLock.release()
            
    def internal_send(self, msg):
        self.safe_send(msg)
        self.on_write_operation(msg)
        
    def on_write_operation(self, msg):
        msg.reset()
        
    def close_connection(self, type="server"):
        self.connectionLock.acquire()
        #self.netview.disconnect(DisconnectEvent("Hey man, is this a dream?"))
        try:
            if self.ssl:
                self.ssl.shutdown(socket.SHUT_RDWR)
                self.ssl.close()
            else:
                self.socket.close()
        except socket.error, msg:
            #self.ed.post(OutputEvent("Internal", msg))
            OutputEvent("Internal", msg).post(self.ed)
        #self.ed.post(ConnectionClosedEvent(type))
        ConnectionClosedEvent(type).post(self.ed)
        self.connectionLock.release()
        return True