Server.py 1.66 KB
import time

from Event.EventDispatcher import EventDispatcher
from Event.EventHandler import EventHandler
import Event.Signal as Signal

from Communication.Manager import CommunicationManager
from Communication.EndPoint import CommunicationEndPoint
from Communication.ConnectEntryPoint import ConnectEntryPoint
from Communication.DatagramEntryPoint import DatagramEntryPoint
from Communication.ProtocolHandler import ProtocolHandler
from Communication.Connector import Connector

from Transport.IoHandler import IoHandler
from Transport.TcpSocket import TcpSocket
from Transport.UdpSocket import UdpSocket

class Server(object):
    def __init__(self, application):
        self._con_mngr   = CommunicationManager()
        self._dispatcher = EventDispatcher()
        
        self._dispatcher.registerHandler(self._con_mngr)
        self._dispatcher.registerHandler(Connector())
        self._dispatcher.registerHandler(IoHandler())
        self._dispatcher.registerHandler(ProtocolHandler())
        self._dispatcher.registerHandler(application)
        Signal.initSignals(self._dispatcher)

    def addEndpoint(self, endpoint):
        self._con_mngr.addEndPoint(endpoint)

    def bindTcp(self, ip, port, protocol):
        self.addEndpoint(ConnectEntryPoint(TcpSocket(ip, port), protocol))
    
    def bindUdp(self, ip, port, protocol):
        self.addEndpoint(DatagramEntryPoint(UdpSocket(ip, port), protocol))

    def addHandler(self, handler):
        self._dispatcher.registerHandler(handler)

    def start(self, heartbeat = None):
        if heartbeat:
            self._dispatcher.setHeartbeat(heartbeat)

        self._dispatcher.start(None)

# vim: set ft=python et ts=8 sw=4 sts=4: