当前位置: 首页>>代码示例>>Python>>正文


Python SimpleWebSocketServer.close方法代码示例

本文整理汇总了Python中SimpleWebSocketServer.SimpleWebSocketServer.close方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleWebSocketServer.close方法的具体用法?Python SimpleWebSocketServer.close怎么用?Python SimpleWebSocketServer.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SimpleWebSocketServer.SimpleWebSocketServer的用法示例。


在下文中一共展示了SimpleWebSocketServer.close方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: LogRecordSocketReceiver

# 需要导入模块: from SimpleWebSocketServer import SimpleWebSocketServer [as 别名]
# 或者: from SimpleWebSocketServer.SimpleWebSocketServer import close [as 别名]
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
开发者ID:TinyOS-Camp,项目名称:DDEA-DEV,代码行数:32,代码来源:main.py

示例2: Server

# 需要导入模块: from SimpleWebSocketServer import SimpleWebSocketServer [as 别名]
# 或者: from SimpleWebSocketServer.SimpleWebSocketServer import close [as 别名]
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()
开发者ID:LoganGirard,项目名称:EyeTribe,代码行数:16,代码来源:EyeReader.py

示例3: socketServerThread

# 需要导入模块: from SimpleWebSocketServer import SimpleWebSocketServer [as 别名]
# 或者: from SimpleWebSocketServer.SimpleWebSocketServer import close [as 别名]
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()
开发者ID:mattfullerton,项目名称:Zoidberg,代码行数:16,代码来源:socketServer.py

示例4: WebSocket_GUI

# 需要导入模块: from SimpleWebSocketServer import SimpleWebSocketServer [as 别名]
# 或者: from SimpleWebSocketServer.SimpleWebSocketServer import close [as 别名]
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
#.........这里部分代码省略.........
开发者ID:Joseph14078,项目名称:raspmusicbox-server,代码行数:103,代码来源:server.py

示例5: WebViewer

# 需要导入模块: from SimpleWebSocketServer import SimpleWebSocketServer [as 别名]
# 或者: from SimpleWebSocketServer.SimpleWebSocketServer import close [as 别名]
class WebViewer(Viewer):

  def __init__(self):
    self.running = False
    self.host_address = ''
    self.port = 8500
    self.server = SimpleWebSocketServer(self.host_address, self.port, SimpleMessager)
    self.game = None

  def init_viewer(self, board, game=None):
    self.board = board
    if not self.game:
      self.game = game
      self.server.game = self.game
    if game:
      if type(self.game.agents[0]) == WebViewer and type(self.game.agents[1]) == WebViewer:
        self.server.configuration = CONFIG_HvH
      elif type(self.game.agents[0]) == WebViewer and type(self.game.agents[1]) != WebViewer:
        self.server.configuration = CONFIG_HvA
      elif type(self.game.agents[0]) != WebViewer and type(self.game.agents[1]) == WebViewer:
        self.server.configuration = CONFIG_AvH
      elif type(self.game.agents[0]) != WebViewer and type(self.game.agents[1]) != WebViewer:
        self.server.configuration = CONFIG_AvA
    else:
      self.server.configuration = CONFIG_R
    if not connectedEvent.is_set():
      self.serverThread = threading.Thread(target=self.server.serveforever)
      self.serverThread.start()
      connectedEvent.wait()

  def run(self):
    """Launch the GUI."""
    if self.running:
      return
    self.running = True
    #self.server.serveforever()

  def replay(self, trace, speed, show_end=False):
    """Replay a game given its saved trace.

    Attributes:
    trace -- trace of the game
    speed -- speed scale of the replay
    show_end -- start with the final state instead of the initial state

    """
    self.trace = trace
    self.speed = speed
    # generate all boards to access them backwards
    self.boards = [trace.get_initial_board()]
    for step in range(len(trace.actions)):
      player, action, t = trace.actions[step]
      b = self.boards[-1].clone()
      b.play_action(action)
      self.boards.append(b)
    self.step = 0
    self.server.initialize_replay(self.trace, self.speed, self.boards)
    self.init_viewer(self.boards[0], None)

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

  def playing(self, step, player):
    print("Step", step, "- Player", player, "is playing")

  def update(self, step, action, player):
    print("Step", step, "- Player", player, "has played", action)
    acknowledgementEvent.clear()
    self.server.update(step, action, player)
    acknowledgementEvent.wait()

  def play(self, percepts, player, step, time_left):
    try:
      hasPlayedEvent.clear()
      self.server.play(percepts, player, step, time_left)
      hasPlayedEvent.wait()
    except EOFError:
      exit(1)
    try:
      return lastActionPlayed
    except (ValueError, AssertionError):
      pass

  def finished(self, steps, winner, reason=""):
    if winner == 0:
      print("Draw game")
    else:
      print("Player 1" if winner > 0 else "Player 2", "has won!")
    if reason:
      print("Reason:", reason)
    self.server.initialize_replay(self.game.trace, 1.0, [])
    self.server.finished(steps, winner, reason)

  signal.signal(signal.SIGINT, close_sig_handler)
  signal.signal(signal.SIGTERM, close_sig_handler)
开发者ID:BenJneB,项目名称:Avalam,代码行数:98,代码来源:gui.py

示例6: qiraplugin_t

# 需要导入模块: from SimpleWebSocketServer import SimpleWebSocketServer [as 别名]
# 或者: from SimpleWebSocketServer.SimpleWebSocketServer import close [as 别名]
class qiraplugin_t(idaapi.plugin_t):
    flags = 0
    comment = "QEMU Interactive Runtime Analyser plugin"
    help = "Visit qira.me for more infos"
    wanted_name = "QIRA Plugin"
    wanted_hotkey = "Alt-F5"

    def __init__(self):
        self.max_comment_len = 100
        self.qira_address = idc.BADADDR
        self.wsserver = None
        self.old_addr = None
        self.port = 3003
        self.addr = None
        self.cmd = None

    def init(self):
        ret = self.start()
        idaapi.msg("[%s] Initialized: Ready to go!\n" % (self.comment,))

        return ret

    def start(self):
        # if __name__ == '__main__':
        server = Thread(target=self.ws_server, args=(3003,))
        try:
            server.start()
            return idaapi.PLUGIN_KEEP
        except AttributeError:
            return idaapi.PLUGIN_SKIP

    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,))

    def ws_send(self, msg):
        if self.wsserver is not None:
            self.start()
        if msg is not None:
            if msg == 'connected':
                for conn in list(CLIENTS):
                    conn.sendMessage(msg)
                    time.sleep(1)
                CLIENTS.append(self)
            elif msg == 'closed':
                CLIENTS.remove(self)
                for conn in list(CLIENTS):
                    conn.sendMessage(msg)
                    time.sleep(1)
            else:
                # print "Tuple: %s" % (self.wsserver.connections.items(),)
                # This one still have errors in both items()/CLIENTS
                for conn in list(self.wsserver.connections.items()):
                    if conn != self:
                        # debugging
                        if DEBUG:
                            idaapi.msg("[%s] ws_send : %s\n" % (self.wanted_name, msg,))
                        conn.sendMessage(msg)
                    time.sleep(0.1)
        else:
            idaapi.msg("[%s] ws_send : Cannot send null\n" % (self.comment,))

    def set_qira_address(self, sea):
        # Check if there is a BreakPoint and delete is before processing.
        if (self.qira_address is not None) and (
                self.qira_address != idc.BADADDR):
            qea = idaapi.toEA(0, self.qira_address)
            if idc.CheckBpt(qea) != -1:
                idaapi.del_bpt(qea)
        # Update qira_address and set BreakPont.
        self.qira_address = sea
        idaapi.add_bpt(self.qira_address, 0, idaapi.BPT_SOFT)
        idc.EnableBpt(self.qira_address, False)
        # debugging
        if DEBUG:
            idaapi.msg(
                "[%s] set_qira_address: 0x%x\n" %
                (self.wanted_name, self.qira_address,))

    def send_names(self):
        qira_names = idaapi.get_nlist_size()
        for i in range(0, qira_names):
            self.cmd = "setname 0x%x %s" % (
                idaapi.get_nlist_ea(i), idaapi.get_nlist_name(i))
            # debugging
            if DEBUG:
                idaapi.msg(
                    "[%s] send_names: EA [0x%x], Name [%s]\n" %
                    (self.wanted_name, idaapi.get_nlist_ea(i),
                     idaapi.get_nlist_name(i),))
            self.ws_send(self.cmd)

    def send_comments(self):
#.........这里部分代码省略.........
开发者ID:Maroc-OS,项目名称:qira,代码行数:103,代码来源:qira.py


注:本文中的SimpleWebSocketServer.SimpleWebSocketServer.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。