Example #1
0
class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
    allow_reuse_address = 1

    def __init__(self,
                 host='localhost',
                 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                 handler=LogRecordStreamHandler):

        SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
        self.abort = 0
        self.timeout = 1
        self.logname = None
        self.requstHandle = None
        self.wsserver = SimpleWebSocketServer('', BASE_WS_PORT, WebSocket)

    def finish_request(self, request, client_address):
        LogRecordStreamHandler(request, client_address, self, self.wsserver)

    def cleanup(self):
        self.wsserver.close()

    def serve_until_stopped(self):
        import select
        abort = 0
        while not abort:
            self.wsserver.servconnman()

            rd, wr, ex = select.select([self.socket.fileno()], [], [],
                                       self.timeout)
            if rd:
                self.handle_request()
            abort = self.abort
Example #2
0
def run_server():
    global server
    server = SimpleWebSocketServer('',
                                   9000,
                                   DetectorHandler,
                                   selectInterval=(1000.0 / 15) / 1000)
    server.serveforever()
Example #3
0
def start_server():
    """
    Start the server in localhost with port 8000
    :return: void
    """
    server = SimpleWebSocketServer('', 8000, SimpleEcho)
    server.serveforever()
Example #4
0
class WSServerThread( threading.Thread ):
	"""
	La clase cliente socket que se levanta como un hilo de proceso 
	independiente.
	"""
	def __init__ ( self, sktServer):
		"""
		Inicializacion de la clase
		"""
		self.wshandlerclass = ''
		self.sktServer = sktServer
		self.wSktServer = SimpleWebSocketServer('', 9000, SimpleEcho)
		threading.Thread.__init__ ( self )


	def setWSHandlerClass(self, instance):
		self.wshandlerclass = instance


	def run ( self ):
		"""
		Una vez inicializada la clase esta es ejecutada en este metodo
		"""
		self.wSktServer.setInvoker(self)
		self.sktServer.attach(self)
		self.wSktServer.serveforever()

	def sendMessage(self, data):
		if self.wshandlerclass != '':
			self.wshandlerclass.send_bytes(data)
Example #5
0
 def run(self):
     print "Starting server on localhost:%d" % self.port
     self.wss = SimpleWebSocketServer('', self.port, BuzzSocket)
     try:
         self.wss.serveforever()
     except:
         print "Buzzws server killed or crashed. Bye!"
Example #6
0
 def __init__(self, host='', port=9999, skipframes=0, **kwargs):
     self.host = host
     self.port = port
     self.skipframes = skipframes + 1
     SimpleWebSocketServer.__init__(self, host, port, BotIOChromeExtensionSocket, selectInterval=0.1)
     Framework.Framework.__init__(self, **kwargs)
     self.serveforever()
Example #7
0
def RunServer():
    try:
        server = SimpleWebSocketServer('', 8080, WS_Collector)
        server.serveforever()
    except KeyboardInterrupt:
        raise
    print 'Stopping Client Socket server'
    def __init__(self):
        self.__version__ = '3.1.3'

        logger_format = '%(asctime)s %(message)s'
        logging.basicConfig(format=logger_format, level=logging.INFO,
                            datefmt="%H:%M:%S", filename='./logfile.log', filemode='w')
        logging.getLogger().addHandler(SysLogHandler(facility=SysLogHandler.LOG_DAEMON, address='/dev/log'))

        self._SIGKILL = False
        self.logging = logging
        self.config = DB('./config.json')

        self.network = Network(self)
        self.display = DisplayContent()
        self.detector = Detector()
        self.ultrasound = Ultrasound(self)
        self.temp = Temp()
        self.server = SimpleWebSocketServer('', 8069, WebSocketServer, self)
        self.cook = Cook(self)
        self.energy = Energy(self)
        self.history = History(self)
        self.audio = Audio(self)
        self.users = Users(self)
        self.automations = Automations(self)

        signal.signal(signal.SIGTERM, self.sig_handler)
        signal.signal(signal.SIGINT, self.sig_handler)

        self.log("Boot: v" + self.__version__)
Example #9
0
class Websocket(object):

    def send_data(self, data):
        for nr, conn in self.server.connections.items():
            conn.sendMessage(data)

    def run(self):
        self.server = SimpleWebSocketServer('', self.port, TestEcho)
        while not self.exit_event.is_set():
            self.server.serveonce()

    def __init__(self, port):
        self.port = port
        self.exit_event = Event()
        self.thread = Thread(target=self.run)
        self.thread.start()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.exit_event.set()
        self.thread.join(10)
        if self.thread.is_alive():
            Utility.console_log('Thread cannot be joined', 'orange')
Example #10
0
def setUp(cls):
    parser = OptionParser(usage="usage: %prog [options]", version="%prog 1.0")
    parser.add_option("--host",
                      default='',
                      type='string',
                      action="store",
                      dest="host",
                      help="hostname (localhost)")
    parser.add_option("--port",
                      default=32768,
                      type='int',
                      action="store",
                      dest="port",
                      help="port (32768)")

    (options, args) = parser.parse_args()
    server = SimpleWebSocketServer(options.host, options.port, cls)

    def close_sig_handler(signal, frame):
        server.close()
        sys.exit()

    signal.signal(signal.SIGINT, close_sig_handler)

    server.serveforever()
Example #11
0
 def _runserver(self):
     self.server = SimpleWebSocketServer(self.superNodeIp, 4141, P2PClientConnectionHandler)
     try:
         print("node starting")
         self.server.serveforever()
     except Exception as e:
         print("websocket server exited: %s" % e)
Example #12
0
def run_server():
    # checking running processes.
    # if the backplane is already running, just note that and move on.

    found_pigpio = False
    found_gammu-smsd = False

    for pid in psutil.pids():
        p = psutil.Process(pid)
        if p.name() == "pigpiod":
            found_pigpio = True
            print("pigpiod is running")
        else:
            continue

    if not found_pigpio:
        call(['sudo', 'pigpiod'])
        print('pigpiod has been started')

    # add gammu-smsd deamon check
    for pid in psutil.pids():
        p = psutil.Process(pid)
        if p.name() == "gammu-smsd":
            found_ = True
            print("gammu-smsd is running")
        else:
            continue

    if not found_gammu-smsd:
        call(['sudo', 'systemctl start gammu-smsd.service'])
        print('gammu-smsd has been started')

    os.system('scratch2&')
    server = SimpleWebSocketServer('', 9000, S2Nadhat)
    server.serveforever()
Example #13
0
class WsServer(object):
    def __init__(self, port):
        self.ws_clients = []
        ws_server = self

        class DataPusher(WebSocket):
            def handleMessage(self):
                pass

            def handleConnected(self):
                logging.info('ws_server: client connected')
                ws_server.ws_clients.append(self)

            def handleClose(self):
                ws_server.ws_clients.remove(self)
                logging.info('ws_server: client closed')

        self.server = SimpleWebSocketServer('', port, DataPusher)

    def start_server(self):
        self.server.serveforever()
        logging.info("ws_server started")

    def broadcast(self, msg):
        msg.update({"ts": time.time()})
        for client in self.ws_clients:
            client.sendMessage(unicode(json.dumps(msg)))
Example #14
0
class WebSockectLCDSimulator:

    def __init__(self):
        self.server = SimpleWebSocketServer('', 8000, WebSocketServer)

    def on_start(self):
        thread = Thread(target=self.runServer)
        thread.start()

    def runServer(self):
        self.server.serveforever()

    def message(self, message):

        #TODO Find special characters and replace with others. For example Volume\x01 to u'Volume\u2600'

        data = unicode(json.dumps({'jsonrpc': '2.0', 'method': 'message', 'params': message }))
        global last_message
        last_message = data
        for client in clients:
            client.sendMessage(data)

    def create_char(self, location, pattern):
        data = unicode(json.dumps({'jsonrpc': '2.0', 'method': 'create_char', 'params': {location: location, pattern: pattern}}))
        for client in clients:
            client.sendMessage(data)

    def on_stop(self):
        self.server.close()

    def is_pressed(self, button):
        if button not in set((InputManager.SELECT, InputManager.RIGHT, InputManager.DOWN, InputManager.UP, InputManager.LEFT)):
            raise ValueError('Unknown button, must be SELECT, RIGHT, DOWN, UP, or LEFT.')
        return pressed_keys[button]
Example #15
0
 def __init__(self):
     self.running = False
     self.host_address = ''
     self.port = 8500
     self.server = SimpleWebSocketServer(self.host_address, self.port,
                                         SimpleMessager)
     self.game = None
Example #16
0
class Server:
    def __init__(self):
        self.server = SimpleWebSocketServer(config.host, config.port, Events)
        self.sockname = self.server.serversocket.getsockname()

    def __call__(self):
        self.server.serveforever()
Example #17
0
 def run(self):
         self._logger.info("Websocket Server started on port %s" % self.port)
         try:
             self.wsd = SimpleWebSocketServer('', self.port, FSWebSocket)
             self.wsd.serveforever()
         except:
             self._logger.error("Websocket not started")
Example #18
0
class WebSocket(util.Threadbase):
    signals = 'message'

    def __init__(self, ip, port):
        global emitter
        super(WebSocket, self).__init__()
        emitter = self
        port = int(port)
        log.info('starting websocket on %s:%i' % (ip, port))
        self.server = SimpleWebSocketServer(ip, port, WebsocketClient)
        self.start()

    def terminate(self):
        log.debug('terminating websocket')
        super().terminate()
        self.server.close()

    @staticmethod
    def send_message(client, message_dict):
        _json = json.dumps(message_dict)
        for _client in clients:
            if not client or _client.address[0] == client.address[0]:
                _client.sendMessage(_json)

    def run(self):
        while not self.terminated:
            self.server.serveonce()
        log.debug('websocket exits')
Example #19
0
def run_server():
    # checking running processes.
    # if the backplane is already running, just note that and move on.
    found_pigpio = False
    found_scratch = False
    print('Starting server')

    for pid in psutil.pids():
        p = psutil.Process(pid)
        if p.name() == "pigpiod":
            found_pigpio = True
            print("pigpiod is running")
        else:
            continue

    if not found_pigpio:
        call(['sudo', 'pigpiod'])
        print('pigpiod has been started')

    for pid in psutil.pids():
        p = psutil.Process(pid)
        if p.name() == "scratch2":
            found_scratch = True
            print("scratch2 is running")
        else:
            continue

    if not found_scratch:
        os.system('scratch2&')
        print('scratch2 has been started')

    server = SimpleWebSocketServer('', 9001, FelixServer)
    server.serveforever()
Example #20
0
class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
    allow_reuse_address = 1

    def __init__(self, host='localhost',
                 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                 handler=LogRecordStreamHandler):

        SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
        self.abort = 0
        self.timeout = 1
        self.logname = None
        self.requstHandle = None
        self.wsserver = SimpleWebSocketServer('', 8081, WebSocket)

    def finish_request(self, request, client_address):
        LogRecordStreamHandler(request, client_address, self, self.wsserver)

    def cleanup(self):
        self.wsserver.close()

    def serve_until_stopped(self):
        import select
        abort = 0
        while not abort:
            self.wsserver.servconnman()

            rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout)
            if rd:
                self.handle_request()
            abort = self.abort
Example #21
0
def RunCNCServer():
    try:
        server = SimpleWebSocketServer('', 8083, WS_Web)
        server.serveforever()
    except KeyboardInterrupt:
        raise
    print 'Stopping CNC server'
Example #22
0
def run_server():
    global server
    server = SimpleWebSocketServer('',
                                   85,
                                   SimpleWSServer,
                                   selectInterval=(1000.0 / 30) / 1000)
    server.serveforever()
Example #23
0
def train_loop(**tmgr_params):
    global train_manager
    train_manager = TrainManager(**tmgr_params)
    server = SimpleWebSocketServer(dist_train_config.WS_HTTP_HOST,
                                   dist_train_config.WS_HTTP_PORT,
                                   ClientConnection)
    server.serveforever()
Example #24
0
class WebSocketServer(Thread):
    def __init__(self, receiver=None):
        Thread.__init__(self)
        self.name = deviceIP
        self.port = wsPort
        self.server = SimpleWebSocketServer(self.name, self.port, HandleServer)
        self._isClosed = False
        self.setDaemon(True)
        if receiver is not None:
            receivers.append(receiver)

    def start(self, name=deviceName):
        mDNSinit('mediadisplay', name)
        logging.info("[Server] starting tcp socket server")
        super(WebSocketServer, self).start()

    def run(self):
        self.server.serveforever()

    def stop(self):
        self.server.close()
        self._isClosed = True

    def broadcast(self, msg):
        if isinstance(msg, str):
            msg = msg.encode('utf-8').decode("utf-8")
        for client in clients:
            client.sendMessage(msg)
            while client.sendq:
                opcode, payload = client.sendq.popleft()
                remaining = client._sendBuffer(payload)
                if remaining is not None:
                    client.sendq.appendleft((opcode, remaining))
                    break
Example #25
0
	def __init__(self, host, port, websocketclass, certfile, keyfile, version = ssl.PROTOCOL_TLSv1):

		SimpleWebSocketServer.__init__(self, host, port, websocketclass)

		self.cerfile = certfile
		self.keyfile = keyfile
		self.version = version
Example #26
0
class WebSocketServer(Thread):
    def __init__(self, name, port):
        Thread.__init__(self)
        self.server = SimpleWebSocketServer(deviceIP, wsPort, HandleServer)
        self._isClosed = False
        mDNSinit()
        BLINKER_LOG('websocket Server init')
        BLINKER_LOG('ws://', deviceIP, ':', wsPort)
        self.setDaemon(True)

    def start(self):
        super(WebSocketServer, self).start()

    def run(self):
        self.server.serveforever()

    def stop(self):
        self.server.close()
        self._isClosed = True

    def broadcast(self, msg):
        if isinstance(msg, str):
            msg = unicode(msg, "utf-8")
        for client in clients:
            client.sendMessage(msg)
            while client.sendq:
                opcode, payload = client.sendq.popleft()
                remaining = client._sendBuffer(payload)
                if remaining is not None:
                    client.sendq.appendleft((opcode, remaining))
                    break
Example #27
0
    def __init__(self, host, port, websocketclass, selectInterval=0.1):

        SimpleWebSocketServer.__init__(self, host, port, websocketclass,
                                       selectInterval)

        self._lock_clients = threading.Lock()
        self._clients = []
Example #28
0
def main(argv):
    if len(argv) == 1 or len(argv) > 3:
        print("Usage:")
        #print(f"  {argv[0]} dbfile [port]")
        print("  {} dbfile [port]".format(argv[0]))
        print("  default port: 8000")
        return

    dbfile = argv[1]

    if len(argv) >= 3:
        try:
            port = int(argv[2])
        except ValueError:
            print("Invalid port")
            return
    else:
        port = 8000

    print("Connecting to db")
    WotServer.pool = DBChunkPool(dbfile)
    WotServer.clients = []

    server = SimpleWebSocketServer('', port, WotServer)
    try:
        server.serveforever()
    except KeyboardInterrupt:
        print("")
        print("Saving recent changes.")
        WotServer.pool.save_changes()
        print("Cleaning up empty chunks from db.")
        WotServer.pool.remove_empty()
        print("Stopped.")
Example #29
0
 def startServer(self):
   self.server = SimpleWebSocketServer(
     config['frontService']['host'],
     config['frontService']['listen'],
     WsHandler
   )
   self.server.serveforever()
Example #30
0
 def __init__(self, ip, port):
     global emitter
     super(WebSocket, self).__init__()
     emitter = self
     port = int(port)
     log.info('starting websocket on %s:%i' % (ip, port))
     self.server = SimpleWebSocketServer(ip, port, WebsocketClient)
     self.start()
def run_server():
    global server
    server = SimpleWebSocketServer('',
                                   9000,
                                   SimpleWSServer,
                                   selectInterval=(1000.0 / 60) / 1000)
    print("run_server")
    server.serveforever()
Example #32
0
 def __init__(self, type=BLINKER_DIY_WIFI):
     Thread.__init__(self)
     self.name = deviceIP
     self.port = wsPort
     self.type = type
     self.server = SimpleWebSocketServer(self.name, self.port, HandleServer)
     self._isClosed = False
     self.setDaemon(True)
Example #33
0
class WebSocketServer(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.server = SimpleWebSocketServer("", WEB_SOCKET_PORT_NUMBER, WebSocketHandler)


    def run(self):
        log.info("Starting WebSocketServer on port %d" % WEB_SOCKET_PORT_NUMBER)
        self.server.serveforever()
Example #34
0
def runServer():
	server = SimpleWebSocketServer("", 8532, VaticServer)

	def close_sig_handler(signal, frame):
		server.close()
		sys.exit()

	signal.signal(signal.SIGINT, close_sig_handler)

	server.serveforever()
Example #35
0
class NetworkServerSocket(Thread):
    def __init__(self, lettre):
        Thread.__init__(self)
        self.server = SimpleWebSocketServer("", portWebSocket, ClientWebSocket)
        print "WEBSOCKET listenning ..."

    def run(self):
        self.server.serveforever()

    def broadcastAll(self, jsonMessage):
        for c in clients:
            c.sendMessage(json.dumps(jsonMessage, ensure_ascii=False))
Example #36
0
 def __init__(self, system):
     from . import skeleton
     SimpleWebSocketServer.__init__(self, '', 9121, _DlalWebSocket)
     self.root = _Root(
         weakref.proxy(system),
         skeleton,
         lambda: FREE,
     )
     self.store = {}
     self.thread = threading.Thread(target=_serve, args=(weakref.ref(self),))
     self.thread.daemon = True
     self.thread.start()
Example #37
0
def serve():

    '''
    class InputServer(WebSocket):
        tilt = 0
        def __init__(self, *args, **kwargs):
            super(InputServer, self).__init__(*args, **kwargs)
            self.runloop = None

        def handleConnected(self):
            print(self.address, 'connected')
            self.runloop = input.KinectLoop(self)
            self.runloop.start()

        def handleClose(self):
            self.runloop.kill()
            print(self.address, 'closed')

        def handleMessage(self):
            self.tilt = int(float(self.data))
    '''
    class InputServer(WebSocket):

        def __init__(self, *args, **kwargs):
            super(InputServer, self).__init__(*args, **kwargs)
            self.kinect = None
            self.oid = None

        def handleConnected(self):
            print self.address, 'connected'
            self.kinect = KinectFactory.create_kinect()
            self.oid = uuid.uuid1()
            self.kinect.add_observer(self.oid, self.send_depth)

        def handleClose(self):
            self.kinect.remove_observer(self.oid)
            print self.address, 'closed'

        def handleMessage(self):
            degs = int(float(self.data))
            self.kinect.set_tilt(degs)

        def send_depth(self, depth):
            self.sendMessage(depth)

    def close_sig_handler(signum, frame):
        server.close()
        KinectFactory.kill()
        sys.exit()

    signal.signal(signal.SIGINT, close_sig_handler)
    server = SimpleWebSocketServer('0.0.0.0', 1337, InputServer)
    server.serveforever()
Example #38
0
def main():
    print("Starting WebSocket ...")
    server = SimpleWebSocketServer('localhost', 8000, DataServer)
    print("WebSocket Ready!")

    def close_sig_handler(signal, frame):
        print("\nClosing WebSocket ...")
        server.close()
        print("Bye!")
        sys.exit()

    signal.signal(signal.SIGINT, close_sig_handler)
    server.serveforever()
Example #39
0
class FSWebSocketServer(FSWebSocketServerInterface):

    def __init__(self):
        super(FSWebSocketServerInterface, self).__init__(group=None)
        self.port = 8010
        self._logger = logging.getLogger(__name__)

    def run(self):
            self._logger.info("Websocket Server started on port %s" % self.port)
            try:
                self.wsd = SimpleWebSocketServer('', self.port, FSWebSocket)
                self.wsd.serveforever()
            except:
                self._logger.error("Websocket not started")
Example #40
0
class FSWebSocketServer(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.port = 8010
        self._logger = logging.getLogger(__name__)

    def run(self):
        #try:
            self._logger.info("Websocket Server started on port %s" % self.port)
            self.wsd = SimpleWebSocketServer('', self.port, FSWebSocket)
            self.wsd.serveforever()
        #except:
        #    self._logger.error("WebSocket Crash!")
Example #41
0
class socketServerThread(threading.Thread):
	def __init__(self, host, port, socketQueue):
		threading.Thread.__init__(self)
		self.cls = socketServer
		self.socketQueue = socketQueue
		self.server = SimpleWebSocketServer(host, port, self.socketQueue, self.cls)
	
	def run(self):
		print "starting Server"
		self.server.serveforever()
		
	def exit(self):
		print "stoping Server"
		self.server.close()
Example #42
0
class Server(Thread):
    def run(self):
        """Starts the thread for the Web Socket Server"""
        host = ""
        port = 8008
        self.server = SimpleWebSocketServer(host, port, Logger)

        print("serving")
        self.server.serveforever()

    def close_sig_handler(self, signal, frame):
        """Function called upon Ctrl+C that kills the program"""
        print("closing")
        self.server.close()
Example #43
0
 def run(self):
     #try:
         self._logger.info("Websocket Server started on port %s" % self.port)
         self.wsd = SimpleWebSocketServer('', self.port, FSWebSocket)
         self.wsd.serveforever()
     #except:
     #    self._logger.error("WebSocket Crash!")
Example #44
0
    def run(self):
        """Starts the thread for the Web Socket Server"""
        host = ""
        port = 8008
        self.server = SimpleWebSocketServer(host, port, Logger)

        print("serving")
        self.server.serveforever()
Example #45
0
	def __init__ ( self, sktServer):
		"""
		Inicializacion de la clase
		"""
		self.wshandlerclass = ''
		self.sktServer = sktServer
		self.wSktServer = SimpleWebSocketServer('', 9000, SimpleEcho)
		threading.Thread.__init__ ( self )
Example #46
0
 def __init__(self, app):
   SimpleWebSocketServer.__init__(self, '', 8080, SimpleEcho)
   QObject.__init__(self)
   
   th = threading.Thread(target=self.serveforever)
   th.daemon = True
   th.start()
   
   self.app = app
   
   for id, iesmas in app.stendas.iesmai.iteritems():
     iesmas.stateChanged.connect(self.onSwitchChanged)
     
   for train in app.trains:
     train.signalChanged.connect(self.onTrainChanged)
     train.speedChanged.connect(self.onTrainChanged)
     
   for ruozas in app.stendas.ruozai:
     ruozas.stateChanged.connect(self.onRoadChanged)
Example #47
0
    def __init__(self, host='localhost',
                 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                 handler=LogRecordStreamHandler):

        SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
        self.abort = 0
        self.timeout = 1
        self.logname = None
        self.requstHandle = None
        self.wsserver = SimpleWebSocketServer('', 8081, WebSocket)
Example #48
0
 def ws_server(self, port):
     if port is None:
         port = self.port
     host = ''
     self.wsserver = SimpleWebSocketServer(host, port, QiraServer, selectInterval=0.1)
     if self.wsserver is not None:
         idaapi.msg("[%s] Starting WS Server\n" % (self.comment,))
         self.wsserver.serveforever()
     else:
         idaapi.msg("[%s] Cannot Start WS Server\n" % (self.comment,))
Example #49
0
	def __init__(self):
		self.server = SimpleWebSocketServer('0.0.0.0', 8000, self.WebSocket_GUI)

		signal.signal(signal.SIGINT, self.close_sig_handler)
		logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)

		thread.start_new_thread(self.thread_main,())
		thread.start_new_thread(self.thread_change,())

		print "Server open!"
Example #50
0
def startServer():
  server = SimpleWebSocketServer('', 12345, SimpleEcho)
  server.serveforever()
Example #51
0
class Server_GUI:
	class WebSocket_GUI(WebSocket):
		def handleMessage(self):
			mode = self.data[:1]
			message = self.data[1:]			
			if (mode == '0'):			# PLAY
				obj_Music.play_pause()
			elif (mode == '1'):			# STOP
				obj_Music.stop()
			elif (mode == '2'):			# PREVIOUS
				obj_Playlist.prev()
			elif (mode == '3'):			# NEXT
				obj_Playlist.button_next()
			elif (mode == '4'):			# VOLUME
				obj_Music.set_volume(float(message))
			elif (mode == '5'):			# PLAY INDEX
				obj_Playlist.play_index(int(message))
			elif (mode == '6'):			# SEEK
				obj_Music.seek(float(message))
			elif (mode == '7'):			# MUTE
				obj_Music.mute_toggle()	
			elif (mode == '8'):			# PLAYLIST CYCLE MODE
				obj_Playlist.change_mode()

		def handleConnected(self):
			print self.address, 'connected'
			Server_GUI.update_all(self);

		def handleClose(self): print self.address, 'closed'

	def __init__(self):
		self.server = SimpleWebSocketServer('0.0.0.0', 8000, self.WebSocket_GUI)

		signal.signal(signal.SIGINT, self.close_sig_handler)
		logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)

		thread.start_new_thread(self.thread_main,())
		thread.start_new_thread(self.thread_change,())

		print "Server open!"

	@staticmethod
	def string_playing(): return '"playing":' + str(obj_Music.get_playing()).lower() + ','

	@staticmethod
	def string_index(): return '"index":' + str(obj_Playlist.index).lower() + ','

	@staticmethod
	def string_files():
		string = '"files":['
		for title in obj_Playlist.array_titles:
			string += '"' + title + '",'
		return string[:-1] + '],'

	@staticmethod
	def string_length():
		string = '"lengths":['
		for length in obj_Playlist.array_length:
			string += str(length) + ','
		return string[:-1] + '],'
	
	@staticmethod
	def string_position(): return '"time":' + str(obj_Music.get_time()) + ','

	@staticmethod
	def string_volume(): return '"volume":' + str(obj_Music.get_volume()) + ','

	@staticmethod
	def string_mute(): return '"mute":' + str(obj_Music.mute).lower() + ','

	@staticmethod
	def string_mode(): return '"mode":' + str(obj_Playlist.mode) + ','
	
	@staticmethod
	def string_cycles():
		string = '"cycles":["'
		for x in obj_Playlist.array_cycles:
			string += x + '","'
		return (string[:-2] + '],').replace("\r", "\n").replace("\n\n", "\n").replace("\n", "\\n")
		
	@staticmethod
	def string_cycles_index():
		string = '"cycles_index":['
		for x in obj_Playlist.array_cycles_index:
			string += str(x) + ','
		return string[:-1] + '],'

	def send_to_all(self, string):
		for conn in self.server.connections.itervalues():
			conn.sendMessage(string)

	def thread_main(self):
		self.server.serveforever()

	@staticmethod
	def update_all(client):
		client.sendMessage("0{" + Server_GUI.string_cycles_index() + Server_GUI.string_cycles() + Server_GUI.string_mode() + Server_GUI.string_mute() + Server_GUI.string_volume() + Server_GUI.string_position() + Server_GUI.string_length() + Server_GUI.string_index() + Server_GUI.string_files() + Server_GUI.string_playing()[:-1] + "}")

	def thread_change(self):
		global running
		array_prev = [None for x in range(6)]
		array_current = [
			obj_Music.get_playing,
			(lambda: obj_Playlist.index),
			obj_Music.get_time,
			obj_Music.get_volume,
			(lambda: obj_Music.mute),
			(lambda: obj_Playlist.mode)
		]
		array_id = [
			'2',
			'3',
			'5',
			'6',
			'7',
			'8'
		]
		array_function = [
			self.string_playing,
			self.string_index,
			self.string_position,
			self.string_volume,
			self.string_mute,
			self.string_mode
		]
		while running:
			for i in range(len(array_current)):
				if (array_prev[i] != array_current[i]()):
					self.send_to_all(array_id[i] + "{" + array_function[i]()[:-1] + "}")
					array_prev[i] = array_current[i]()
			time.sleep(1.0/15.0)

	def close_sig_handler(self, signal, frame):
		self.server.close()
def startWebSocketServer():
  socketServer = SimpleWebSocketServer('', websocket_port, TestWebSocket)
  socketServer.serveforever()
Example #53
0
 def run(self):
     print('trying to initialize websocket server...')
     handler = make_handler_class(self.fcd, self.fcd_write_func)
     server = SimpleWebSocketServer('', 8926, handler)
     print('websocket server is running')
     server.serveforever()
def startServer():
    server = SimpleWebSocketServer('', 8080, SockClient)
    server.serveforever()
Example #55
0
import signal, sys, ssl
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer, SimpleSSLWebSocketServer
from optparse import OptionParser

clients = []
class SimpleChat(WebSocket):

    def handleMessage(self):
        words = self.data.split("\r\n")
        print("\nCount={0}".format(len(words)))
        for w in words:
            print ''.join(' {:02x}'.format(x) for x in w)

    def handleConnected(self):
       print self.address, 'connected'
       for client in clients:
          client.sendMessage(self.address[0] + u' - connected')
       clients.append(self)

    def handleClose(self):
       clients.remove(self)
       print self.address, 'closed'
       for client in clients:
          client.sendMessage(self.address[0] + u' - disconnected')

server = SimpleWebSocketServer('', 8000, SimpleChat)
server.serveforever()
Example #56
0
    def handleConnected(self):
        print self.address, 'connected'

    def handleClose(self):
        #car.stop()
        print self.address, 'closed'

if __name__ == '__main__':
    os.chdir(os.path.dirname(os.path.realpath(__file__)) + '/www')
    SocketServer.TCPServer.allow_reuse_address = True
    httpserver = SocketServer.TCPServer(
        ('', HTTP_PORT), SimpleHTTPRequestHandler)
    print('car http server port: %d' % HTTP_PORT)
    httpd = threading.Thread(target=httpserver.serve_forever)
    httpd.start()
    websocket = SimpleWebSocketServer('', WEBSOCKET_PORT, CommandWebsocket)

    def close_sig_handler(signal, frame):
        #car.quit()
        httpserver.shutdown()
        httpd.join()
        websocket.close()

        print('quit')
        sys.exit()

    signal.signal(signal.SIGINT, close_sig_handler)
    while True:
        websocket.serveforever()
        if grove_sound_sensor.read_sound_sensor_values() >= SoundLimen:
            if Flag == 0:
Example #57
0
	def __init__(self, host, port, socketQueue):
		threading.Thread.__init__(self)
		self.cls = socketServer
		self.socketQueue = socketQueue
		self.server = SimpleWebSocketServer(host, port, self.socketQueue, self.cls)
Example #58
0
#!/usr/bin/python
import sys
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer

class SimpleEcho(WebSocket):

	def handleMessage(self):
		if self.data is None:
			self.data = ''

		# echo message back to client
		self.sendMessage(str(self.data))
		print str(self.data)
		sys.stdout.flush()

	def handleConnected(self):
		print self.address, 'connected'

	def handleClose(self):
		print self.address, 'closed'
	
#START
server = SimpleWebSocketServer('', 8000, SimpleEcho)

while True:
	server.servenow()