示例#1
0
class WebSocketThread(threading.Thread):
    websocks = websocket_server.WebsocketServer(WEBSOCKET_PORT, '0.0.0.0')

    def send(self, msg):
        #print("websocket: sending message \"%s\"" % msg)
        self.websocks.send_message_to_all(msg)

    def client_connected(self, client, server):
        print("websocket: client connected, given id %d" % client['id'])
        server.send_message(client, "%d" % client['id'])

    def client_left(self, client, server):
        if 'id' in client:
            print("websocket: client %d left" % client['id'])
            gamestate.kill(client['id'])

    def message_received(self, client, server, msg):
        print("websocket: received message \"%s\" from client %d" %
              (msg, client['id']))
        if msg == "join":
            gamestate.join(client['id'])
        else:
            id, dir = msg.split()
            gamestate.handle(int(id), dir)

    def run(self):
        self.websocks.set_fn_new_client(self.client_connected)
        self.websocks.set_fn_client_left(self.client_left)
        self.websocks.set_fn_message_received(self.message_received)
        print("websocket: serving websocket at port", WEBSOCKET_PORT)
        self.websocks.serve_forever()
示例#2
0
def __init__ser():
    global server, serialport
    server = websocket_server.WebsocketServer(12315)
    server.set_fn_new_client(new_client)
    server.set_fn_client_left(client_left)
    server.set_fn_message_received(message_received)
    # 串口
    serialport = MySerialPort()
示例#3
0
 def __init__(self, service_handler):
     """
     :param service_handler: a dictionary of functional handlers, where the key maps to the message as a string
     :type service_handler:
     """
     self.service_handler = service_handler
     self.ws_server = websocket_server.WebsocketServer(8080)
     self.ws_server.set_fn_message_received(self.message_handler)
     self.bootstrap_passed = False
     self.validator = {}
示例#4
0
    def __init__(self,
                 client_html_location,
                 message_handler,
                 selenium_tester=None):
        print("Listening for Websockets request on port 8080")
        self.ws_server = websocket_server.WebsocketServer(8080)
        self.ws_server.set_fn_message_received(message_handler)

        # Slight race condition here on start-up
        self.selenium_tester = selenium_tester
        self.delay_open_ui(client_html_location)
        self.ws_server.run_forever()
示例#5
0
def main(serial):
    loop = asyncio.get_event_loop()
    dev = SerialBLE(serial, loop=loop)

    server = websocket_server.WebsocketServer(8001)
    server.set_fn_message_received(lambda client, server, message: loop.
                                   create_task(dev.write(json.loads(message))))
    threading.Thread(
        target=server.run_forever,
        daemon=True,
    ).start()
    loop.run_forever()
示例#6
0
    def __init__(self, port=8080):
        threading.Thread.__init__(self)
        self.host = "0.0.0.0"
        self.port = port
        self.requests = queue.Queue(maxsize=50)
        self.running = False
        self.clients = []

        self.server = websocket_server.WebsocketServer(self.port, self.host)
        self.server.set_fn_new_client(self.connected)
        self.server.set_fn_client_left(self.disconnected)
        self.server.set_fn_message_received(self.received)

        self.next_id = 0
示例#7
0
    def __init__(self, *, name: str = "websocketServer", port: int):

        super().__init__()  # never forget!

        self.daemon = True
        self.name = name

        setproctitle.setproctitle('EE:' + name)

        self.engine = websocket_server.WebsocketServer(
            port=port, host='0.0.0.0')  # inaddr_any

        self.engine.set_fn_new_client(self.welcome)
        self.engine.set_fn_message_received(self.repeater)
        self.engine.set_fn_client_left(self.goodbye)

        self.logger = logging.getLogger("Log")
示例#8
0
 def __init__(self,
              port,
              client_file_location,
              message_router,
              dir_levels_to_serve=0,
              start_browser=True,
              serve_ui=True,
              server_certfile=None,
              browser_pref=None):
     self.ws_url = "ws://localhost:" + str(port)
     self.ws_server = websocket_server.WebsocketServer(port)
     self.ws_server.set_fn_message_received(self.message_received)
     self.message_router = message_router
     self.message_count = 0
     self.client_file_location = os.path.abspath(client_file_location)
     self.serve_ui = serve_ui
     self.start_browser = start_browser
     self.ui_file_server = None
     self.thread_ui_file_server = None
     self.dir_levels_to_serve = dir_levels_to_serve
     self.shutdown_lock = threading.Lock()
     self.server_certfile = server_certfile
     self.browser_pref = browser_pref
示例#9
0
#q = Queue.Queue()

#def passing_global_variable(v):
#  global message_from_ws
#  message_from_ws = v
def message_received(client, server, message):
  #server.send_message_to_all(message)
  #passing_global_variable(message)
  
  global message_from_ws
  message_from_ws = message 
  #global q
  #q.put(message)
  
server = websocket_server.WebsocketServer(8008,host='0.0.0.0')
server.set_fn_message_received(message_received)
try:
  #thread.start_new_thread(server.run_forever,())
  t_ws = threading.Thread(target=server.run_forever)
  t_ws.daemon = True
  t_ws.start()
except:
  pass

#os.system("kill `pgrep -f pythonCode`")
#os.system("python /root/pythonCode.py&")

#try:
#  thread.start_new_thread(process_run,(subprocess,server))
#except:
示例#10
0
        def thread_function():
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

            ex = exchanger.Exchanger()

            try:
                # start http server for browser
                hh = http_handler.GhostTextHttpHandlerFactory(8765)
                http_svr = tcp_server.TcpServer(loop, hh)
                try:
                    http_svr.start()
                except:
                    print('fail to start tcp svr on localhost:4001')
                    http_svr = None
                    raise ServerStartException

                # start tcp server for vim channel to connect
                ch = vim_channel_handler.Channel(ex.channel_rx_coro())
                ch_svr = tcp_server.TcpServer(loop, ch)
                try:
                    ch_svr.start(host='localhost', port='4002')
                except:
                    print('fail to start channel svr on localhost:4002')
                    ch_svr = None
                    raise ServerStartException

                # exchanger needs channel to send message
                ex.channel = ch

                # start websockets server
                ws_manager = vim_websocket_handler.Manager(
                    ex.websocket_rx_coro())
                ws_svr = websocket_server.WebsocketServer(loop, ws_manager)

                try:
                    ws_svr.start()
                except:
                    print('fail to start channel svr on localhost:4002')
                    ws_svr = None
                    raise ServerStartException

                # exchanger needs ws_manager to send message
                ex.ws_manager = ws_manager
            except ServerStartException:
                self.running = False
                self.start_event.set()
            else:
                # run until the stop request event will be set
                self.running = True
                self.start_event.set()
                loop.run_until_complete(wait_for_stop(loop))

            # teardown
            try:
                ws_svr.close()
                ch_svr.close()
                http_svr.close()
                loop.close()
            except:
                pass
示例#11
0
def new_game_board(hostname, portnumber, queue, game_id):
    """
    This holds the environment for a new game board process.

    :param hostname: the hostname which the game board whill run on
    :param portnumber: the port-number which the web socket will listen on
    :param  queue: the process queue which is used for inter process communication
    :param game_id: the id number of the current game environment
    """

    s = Server()
    num_clients = ClientCount()
    ws = websocket_server.WebsocketServer(portnumber, hostname)

    def client_leave(client, server):
        """
        This function will be run when a client disconnects from the server. 

        :param client: the new client dictionary
        :param server: a reference to the WebSocket Server
        """

        if not num_clients.game_started:
            queue.put(("new_board", game_id))
            time.sleep(0.1)
            ws.shutdown()
            queue.put(("exit", game_id))

        num_clients.dec()
        if num_clients.val() <= 0:
            ws.shutdown()
            queue.put(("exit", game_id))

    def new_client(client, server):
        """
        This function will be run when a new client connects to the server. 

        :param client: the new client dictionary
        :param server: a reference to the WebSocket Server
        """
        num_clients.inc()

    def recv_message(client, server, message):
        """
        This function will be run when a message is recieved from one of
        the connected clients.

        :param client: the client dictionary which the message came from
        :param server: a reference to the WebSocket Server
        :param message: the message which has been received
        """
        print("Received: {}".format(message))
        json_string = json.loads(message)

        if json_string["type"] == "player_join":
            new_id = s.next_id()

            if num_clients.game_started:
                del server.clients[server.clients.index(client)]
                return

            response_json = {
                "type": "player_join_ack",
                "key": json_string["key"],
                "your_id": new_id,
                "current_player": s.num_players(),
                "expects": 4,
                "game_start": False if s.num_players() < 4 else True,
            }
            response_json_string = json.dumps(response_json)
            server.send_message_to_all(response_json_string.encode("utf-8"))
            print("Sending: {}".format(response_json_string))
            if s.num_players() == 4:
                s.start_game()

                board_sync_json = s.game_state()
                board_sync_string = json.dumps(board_sync_json)
                server.send_message_to_all(board_sync_string.encode("utf-8"))
                print("Sending: {}".format(board_sync_string))

                response_json = {
                    "type": "your_turn",
                    "source": 1,
                }
                response_json_string = json.dumps(response_json)
                server.send_message_to_all(
                    response_json_string.encode("utf-8"))
                print("Sending: {}".format(response_json_string))

                num_clients.game_started = True

                queue.put(("new_board", game_id))

        elif json_string["type"] == "start_game_now":
            s.start_game()
            response_json = {
                "type": "player_join_ack",
                "key": -1,
                "your_id": -1,
                "current_player": s.num_players(),
                "expects": 4,
                "game_start": True,
            }
            response_json_string = json.dumps(response_json)
            server.send_message_to_all(response_json_string.encode("utf-8"))
            print("Sending: {}".format(response_json_string))

            board_sync_json = s.game_state()
            board_sync_string = json.dumps(board_sync_json)
            server.send_message_to_all(board_sync_string.encode("utf-8"))
            print("Sending: {}".format(board_sync_string))

            response_json = {
                "type": "your_turn",
                "source": 1,
            }
            response_json_string = json.dumps(response_json)
            server.send_message_to_all(response_json_string.encode("utf-8"))
            print("Sending: {}".format(response_json_string))

            num_clients.game_started = True

            queue.put(("new_board", game_id))

        elif json_string["type"] == "roll":
            player_id = json_string["source"]
            if s.new_roll:
                dice1, dice2 = s.roll_dice()
            else:
                dice1, dice2 = 0, 0
                s.new_roll = False
            response_json = {
                "type": "roll_result",
                "source": player_id,
                "result": [dice1, dice2],
            }

            response_json_string = json.dumps(response_json)
            server.send_message_to_all(response_json_string.encode("utf-8"))
            print("Sending: {}".format(response_json_string))

            s.current_turn_generator = s.take_turn(player_id, dice1, dice2)
            try:
                msg = s.current_turn_generator.send(None)
                if msg.startswith("action_square") or msg.startswith(
                        "paid_rent"):
                    what_happened = msg.split("|")[1]
                    response_json = {
                        "type": "textual_update",
                        "text": what_happened,
                    }

                    response_json_string = json.dumps(response_json)
                    server.send_message_to_all(
                        response_json_string.encode("utf-8"))
                    print("Sending: {}".format(response_json_string))

            except PlayerLostError:
                response_json = {
                    "type": "player_lose",
                    "player": s.current_player(),
                }
                response_json_string = json.dumps(response_json)
                server.send_message_to_all(
                    response_json_string.encode("utf-8"))
                print("Sending: {}".format(response_json_string))

                board_sync_json = s.game_state()
                board_sync_string = json.dumps(board_sync_json)
                server.send_message_to_all(board_sync_string.encode("utf-8"))
                print("Sending: {}".format(board_sync_string))

                s.next_player()
                new_current_player_id = s.current_player()
                response_json = {
                    "type": "your_turn",
                    "source": new_current_player_id,
                }
                response_json_string = json.dumps(response_json)
                server.send_message_to_all(
                    response_json_string.encode("utf-8"))
                print("Sending: {}".format(response_json_string))

        elif json_string["type"] == "buy":
            if json_string["property"] == -1:
                s.current_turn_generator.send("no_buy")

            else:
                s.current_turn_generator.send("buy")
                response_json = {
                    "type": "buy_ack",
                    "source": s.current_player(),
                    "property": json_string["property"],
                }

                response_json_string = json.dumps(response_json)
                server.send_message_to_all(
                    response_json_string.encode("utf-8"))
                print("Sending: {}".format(response_json_string))

        elif json_string["type"] == "auction":
            response_json = {
                "type": "auction_start",
                "competitor": s.get_all_players(),
                "source": json_string["source"],
                "property": json_string["property"],
                "base_price": 10,
            }
            response_json_string = json.dumps(response_json)
            server.send_message_to_all(response_json_string.encode("utf-8"))
            print("Sending: {}".format(response_json_string))
            s.current_bidders = s.get_all_players()
            s.bids = {}
            s.auction_property = json_string["property"]
            s.current_turn_generator.send("auction")

        elif json_string["type"] == "auction_bid":
            player_id = json_string["source"]
            bid_amount = json_string["price"]
            if bid_amount != 0:
                s.bids[player_id] = bid_amount
            else:
                s.current_bidders.remove(player_id)

            response_json = {
                "type": "auction_bid_ack",
                "source": json_string["source"],
            }
            response_json_string = json.dumps(response_json)
            server.send_message_to_all(response_json_string.encode("utf-8"))
            print("Sending: {}".format(response_json_string))

            if len(s.current_bidders) == 0:
                response_json = {
                    "type": "auction_finished",
                    "property": s.auction_property,
                    "price": 0,
                    "winner": -1,
                }
                response_json_string = json.dumps(response_json)
                server.send_message_to_all(
                    response_json_string.encode("utf-8"))
                print("Sending: {}".format(response_json_string))

                s.current_turn_generator.send((None, 0))

            elif len(s.bids) == len(s.current_bidders):
                max_bid_players, max_bid = s.get_auction_result()
                if len(max_bid_players) == 1:
                    response_json = {
                        "type": "auction_finished",
                        "property": s.auction_property,
                        "price": max_bid,
                        "winner": max_bid_players[0],
                    }
                    response_json_string = json.dumps(response_json)
                    server.send_message_to_all(
                        response_json_string.encode("utf-8"))
                    print("Sending: {}".format(response_json_string))

                    s.current_turn_generator.send(
                        (max_bid_players[0], max_bid))

                else:
                    response_json = {
                        "type": "auction_start",
                        "competitor": max_bid_players,
                        "source": -1,
                        "property": s.auction_property,
                        "base_price": max_bid,
                    }
                    response_json_string = json.dumps(response_json)
                    server.send_message_to_all(
                        response_json_string.encode("utf-8"))
                    print("Sending: {}".format(response_json_string))
                    s.current_bidders = max_bid_players
                    s.bids = {}

        elif json_string["type"] == "end_turn":
            if s.is_valid_player(json_string["source"]):
                board_sync_json = s.game_state()
                board_sync_string = json.dumps(board_sync_json)
                server.send_message_to_all(board_sync_string.encode("utf-8"))
                print("Sending: {}".format(board_sync_string))

                re_check_location, new_roll = s.current_turn_generator.send(
                    None)
                if not re_check_location:
                    s.next_player()
                    s.new_roll = True
                else:
                    s.new_roll = new_roll

                new_current_player_id = s.current_player()
                response_json = {
                    "type": "your_turn",
                    "source": new_current_player_id,
                }
                response_json_string = json.dumps(response_json)
                server.send_message_to_all(
                    response_json_string.encode("utf-8"))
                print("Sending: {}".format(response_json_string))

        elif json_string["type"] == "chat":
            response_json = json_string
            response_json["type"] = "chat_sync"
            response_json_string = json.dumps(response_json)
            server.send_message_to_all(response_json_string.encode("utf-8"))
            print("Sending: {}".format(response_json_string))

        elif json_string["type"] == "build_house":
            player_id = json_string["source"]
            property_id = json_string["property"]
            try:
                if json_string["sell"]:
                    s.sell_house(player_id, property_id)
                    current_rent = s.get_current_rent(property_id)
                    num_houses = s.get_num_houses(property_id)
                    gained_money = s.get_sell_value(property_id)

                    response_json = {
                        "type": "build_ack",
                        "property": json_string["property"],
                        "source": json_string["source"],
                        "current_rent": current_rent,
                        "sell": True,
                        "num_houses": num_houses,
                        "gained_money": gained_money,
                    }
                    response_json_string = json.dumps(response_json)
                    server.send_message_to_all(
                        response_json_string.encode("utf-8"))
                    print("Sending: {}".format(response_json_string))

                else:
                    s.build_house(player_id, property_id)
                    current_rent = s.get_current_rent(property_id)
                    num_houses = s.get_num_houses(property_id)
                    response_json = {
                        "type": "build_ack",
                        "property": json_string["property"],
                        "source": json_string["source"],
                        "current_rent": current_rent,
                        "sell": False,
                        "num_houses": num_houses,
                    }
                    response_json_string = json.dumps(response_json)
                    server.send_message_to_all(
                        response_json_string.encode("utf-8"))
                    print("Sending: {}".format(response_json_string))
            except BuildException:
                pass

        elif json_string["type"] == "pay_bail":
            player_id = json_string["source"]
            if json_string["get_out_of_jail_free"]:
                s.leave_jail(player_id, free_card=True)
            else:
                s.leave_jail(player_id, free_card=False)

            board_sync_json = s.game_state()
            board_sync_string = json.dumps(board_sync_json)
            server.send_message_to_all(board_sync_string.encode("utf-8"))
            print("Sending: {}".format(board_sync_string))

        elif json_string["type"] == "mortgage_property":
            player_id = json_string["player"]
            property_id = json_string["property"]
            try:
                if json_string["unmortgage"]:
                    s.unmortgage_property(player_id, property_id)
                else:
                    s.mortgage_property(player_id, property_id)

                response_json = {
                    "type": "mortgage_property_ack",
                    "property": property_id,
                    "player": player_id,
                    "unmortgage": json_string["unmortgage"],
                }
                response_json_string = json.dumps(response_json)
                server.send_message_to_all(
                    response_json_string.encode("utf-8"))
                print("Sending: {}".format(response_json_string))

                board_sync_json = s.game_state()
                board_sync_string = json.dumps(board_sync_json)
                server.send_message_to_all(board_sync_string.encode("utf-8"))
                print("Sending: {}".format(board_sync_string))

            except MortgageException:
                pass

    ws.set_fn_new_client(new_client)
    ws.set_fn_message_received(recv_message)
    ws.set_fn_client_left(client_leave)
    ws.run_forever()
示例#12
0
        print(the_traceback)
        return je3.server.response(code=500,
                                   body=t.pre(the_traceback).encode())


multiprocessing.Process(target=lambda: http.server.ThreadingHTTPServer(
    ('192.168.1.3', int(sys.argv[1])),
    je3.server.handler(handle_http, connection_timeout=1)).serve_forever()
                        ).start()


def handle_touch(client, server, message):
    event = types.SimpleNamespace(**json.loads(message))
    width, height = pyautogui.size()
    if event.type != 'touchcancel':
        x, y = bounds[:2]
        width, height = bounds[2] - x, bounds[3] - y
        pyautogui.moveTo(bounds[0] + event.x * width,
                         bounds[1] + event.y * height)
    dict(
        touchstart=pyautogui.mouseDown,
        touchend=pyautogui.mouseUp,
        touchcancel=pyautogui.mouseUp,
        touchmove=lambda: None,
    )[event.type]()


server = websocket_server.WebsocketServer(9001, host='192.168.1.3')
server.set_fn_message_received(handle_touch)
server.run_forever()