Ejemplo n.º 1
0
def game_handler(connection:server.GameConnection,s:'Game State'):
    '''Takes the game state and game connection as arguments and calls the game_play function
       and the board_display function for each players move and returns the winning player
    '''
    print('WELCOME TO CONNECT 4 GAME')
    
    username=read_username()
    server.send(connection,'I32CFSP_HELLO '+username)
    print(server.read_line(connection))
    
    server.send(connection,'AI_GAME ')
    print(server.read_line(connection))
   
    while True:
        if connectfour.winning_player(s)==connectfour.NONE:
            if s.turn==connectfour.RED:
                print('Player ',username)
                s=game_play(s,connection)
                common_file.board_display(s)
            elif s.turn==connectfour.YELLOW:
                print('Player AI')
                s=common_file.game_move(s,server.read(connection))                  
                if s==None:
                    print('Invalid move by Server')
                    server.close(connection)
                    return None
                common_file.board_display(s)                             
        elif connectfour.winning_player(s)==connectfour.RED:
            return username
        elif connectfour.winning_player(s)==connectfour.YELLOW:
            return 'AI'
Ejemplo n.º 2
0
def do_process():
    print("TRAITEMENT")

    li_ville = request.forms.ville
    li_sport = request.forms.sport
    li_niv = request.forms.niveau

    conn = server.start()

    if li_ville == "":
        res = server.query_act(conn, li_sport)
    else:
        if li_sport == "":
            res = server.query_city(conn, li_ville)
        else:
            if li_niv == "":
                res = server.query_city_and_act(conn, li_ville, li_sport)
            else:
                res = server.query_city_and_act_and_niv(
                    conn, li_ville, li_sport, li_niv)

    server.close(conn)
    print(res)
    my_dict = {'res': res, 'nbRes': len(res)}
    return template("Template.html", my_dict)
Ejemplo n.º 3
0
 def sendEmptyTable(client):
     from server import close
     stablstr = "[stabl|e0:        :00,e0:        :00,e0:        :00,e0:        :00,e0:        :00,e0:        :00,e0:        :00|52,52,52,52|0]"
     try:
         client.socket.send(stablstr)
     except socket.error:
         close(client.socket)
Ejemplo n.º 4
0
def main(my_ip, my_port):
    if not server.init(my_ip, my_port, functions):
       print " - Not able to initiate server!"
       return 
    print " Listening on %s:%s" % (my_ip, my_port) 
    print " <CTRL-C> to quit."
    try:
        server.start_listen()
    except KeyboardInterrupt:
        server.close()
Ejemplo n.º 5
0
 async def serve(cls, ip: str, port: int) -> None:
     loop = aio.get_event_loop()
     # on_con_lost = loop.create_future()
     # cls.queue = janus.Queue(loop=loop)
     # Client.ClientProtocol.queue = cls.queue
     server = await loop.create_server(cls, ip, port)
     addr = cast(List, server.sockets)[0].getsockname()
     print(f"Control Serving on {addr}")
     try:
         await server.serve_forever()
     except aio.CancelledError:
         await cls.shutdown(addr, loop)
         server.close()
Ejemplo n.º 6
0
 def sendhand(con, hand):
     from server import close
     handstr = "[shand|"  # build string, then try to send it off
     for i in hand:
         handstr = handstr + "%02d," % i
     while len(handstr) < 61:
         handstr += "52,"
     handstr = handstr[0:len(handstr) - 1] + "]"
     try:
         con.send(handstr + "\n")
     except:
         close(con)
         return -1
     return 0
Ejemplo n.º 7
0
def main(my_ip, my_port):
    try:
       if not server.init(my_ip, my_port, functions):
           print " - Not able to initiate server. Exiting."
           return
    except socket.error as err:
       print err
       print " - Not able to initiate server. Exiting."
       return 
    print " Oxide server listening on %s:%s" % (my_ip, my_port) 
    print " <CTRL-C> to quit."
    try:
        server.start_listen()
    except KeyboardInterrupt:
        print " - Caught <CTRL-C> closing server"
        server.close()
Ejemplo n.º 8
0
def serve_homepage():
    conn = server.start()

    liste_ville = server.get_city(conn)
    liste_sport = server.get_sport(conn)
    liste_niveau = server.getNiveau(conn)

    print(liste_niveau)

    server.close(conn)

    my_dict = {
        'listeSport': liste_sport,
        'listeVille': liste_ville,
        'listeNiveau': liste_niveau
    }
    return template("index.html", my_dict)
Ejemplo n.º 9
0
 def Play():
     from server import close
     if len(Table.handof[Table.curplayer]
            ) == 0:  # check if the current player has cards
         Table.getNextPlayer()  # get next player if not
     if Table.oneLeft(
     ):  # check if there's only one player with cards/alive at the table
         Table.addLast(
         )  # add him to finished if so, set state to NEWGAME and let the server main loop handle it from there
         gvals.state = D_STATE.NEWGAME
         return
     Table.checkStatus(
     )  # otherwise, check the status of the table (if everyone else passed, i.e. new round is necessary)
     tablestring = Table.tableStr(
     )  # prepare the string for broadcasting the table message
     for c in gvals.clientlist:  # broadcast it to everyone still connected
         try:
             c.socket.send(tablestring + '\n')
         except socket.error:
             close(c.socket)
     gvals.to_time = time.time()  # update time for timeout value
Ejemplo n.º 10
0
 def swap():
     Table.wcard = Table.handof[7].pop(
     )  # pull highest rank card from scumbad
     errval = Table.sendhand(
         Table.player[1].socket,
         Table.handof[1])  # attempt to send the hand to the warlord
     try:  # attempt to send the swap message to the warlord
         Table.player[1].socket.send("[swapw|%02d]\n" % Table.wcard)
     except socket.error:
         close(Table.player[1].socket)
         errval = -1
     Table.handof[1].append(Table.wcard)  # add to warlord's hand
     Table.handof[1].sort()  # keep it sorted
     Table.curplayer = 1  # we've got swap scenario, that means rank matters, so warlord goes first
     gvals.state = D_STATE.WTIMEOUT  # warlord timeout state
     gvals.to_time = time.time()
     if errval == -1:  # unable to send message to warlord, so give the card back to the scumbag
         print "Unable to send swap message to warlord."
         print "----------------------------------"
         Table.handof[7].appendleft(Table.wcard)
         Table.getNextPlayer()  # get the next player
         Table.StartGame()  # and start the game
Ejemplo n.º 11
0
def main():
    """
    Run an SNI-enabled server which selects between a few certificates in a
    C{dict} based on the handshake request it receives from a client.
    """
    port = socket()
    port.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    port.bind(('', 8443))
    port.listen(3)

    print 'Accepting...',
    stdout.flush()
    server, addr = port.accept()
    print 'accepted', addr

    server_context = Context(TLSv1_METHOD)
    server_context.set_tlsext_servername_callback(pick_certificate)

    server_ssl = Connection(server_context, server)
    server_ssl.set_accept_state()
    server_ssl.do_handshake()
    server.close()
Ejemplo n.º 12
0
def main():
    """
    Run an SNI-enabled server which selects between a few certificates in a
    C{dict} based on the handshake request it receives from a client.
    """
    port = socket()
    port.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    port.bind(('', 8443))
    port.listen(3)

    print 'Accepting...',
    stdout.flush()
    server, addr = port.accept()
    print 'accepted', addr

    server_context = Context(TLSv1_METHOD)
    server_context.set_tlsext_servername_callback(pick_certificate)

    server_ssl = Connection(server_context, server)
    server_ssl.set_accept_state()
    server_ssl.do_handshake()
    server.close()
Ejemplo n.º 13
0
def reloader(mp):
    """
    Watch files for changes, then restart the process if required.
    """
    files = dict()
    for i in sys.modules.values():
        if hasattr(i, "__file__"):
            files[i.__file__] = (i,os.stat(i.__file__)[stat.ST_MTIME])
    while True:
        yield from asyncio.sleep(1)
        for f in files:
            mod, mt = files[f]
            try:
                nmt = os.stat(f)[stat.ST_MTIME]
            except:
                #force a restart if something bad happens.
                nmt = mt - 1;
            if mt != nmt:
                print("Change detected, restarting...")
                if mp is not None:
                    mp.terminate() 
                yield from nwdb.close()
                yield from server.close()
                os.execl(__file__, "")
Ejemplo n.º 14
0
def receive_signal(signum, stack):
    store.close()
    my_scheduler.close()
    server.close()
Ejemplo n.º 15
0
 async def __aexit__(self, exc_type, exc_val, exc_tb):
     for server in self.servers:
         server.close()
Ejemplo n.º 16
0
        # Start the VNC Server
        self.status.config(text="Starting VNC Server...")
        self.status.update_idletasks()
        processes.append(vnc.server_start(password=password))
        time.sleep(2)

        self.status.config(text="Waiting for remote client...")
        self.status.update_idletasks()
        #vncprocess = vnc.server_connect(port=port) # Attempt to connect to the VNC viewer
        #output = vncprocess.communicate() # Retrieve the command output
        #print output
        #processes.append(vncprocess) # Append to the list of processes

root = Tk()
root.title("ShowYourDesktop")
if os.name == "nt": root.wm_iconbitmap("showyourdesktop.ico")
app = App(root)
root.mainloop()

# End any extra processes
for process in processes:
    try:
        print "Killed", process.pid
        process.kill()
    except:
        print "Unexpected error:", sys.exc_info()[0]

# Remove the session from the server's database if it was shared.
if shared:
    server.close(shared)
Ejemplo n.º 17
0
        self.status.update_idletasks()
        processes.append(vnc.server_start(password=password))
        time.sleep(2)

        self.status.config(text="Waiting for remote client...")
        self.status.update_idletasks()
        # vncprocess = vnc.server_connect(port=port) # Attempt to connect to the VNC viewer
        # output = vncprocess.communicate() # Retrieve the command output
        # print output
        # processes.append(vncprocess) # Append to the list of processes


root = Tk()
root.title("ShowYourDesktop")
if os.name == "nt":
    root.wm_iconbitmap("showyourdesktop.ico")
app = App(root)
root.mainloop()

# End any extra processes
for process in processes:
    try:
        print "Killed", process.pid
        process.kill()
    except:
        print "Unexpected error:", sys.exc_info()[0]

# Remove the session from the server's database if it was shared.
if shared:
    server.close(shared)
Ejemplo n.º 18
0
def teardown():
    server.close()
Ejemplo n.º 19
0
 def shutdown():
     loop.stop()
     server.close()
Ejemplo n.º 20
0
		self.log_queue.put(line)
	
	def info(self, i):
		line = u'[%s] [INFO] %s' % (str(self.get_readable_time()), i)
		self.log_queue.put(line)
	
	def process_queue(self):
		while not self.abort:
			try:
				log_line = self.log_queue.get(timeout=1)
				print log_line
				self.file.write("%s\n" % log_line)
				self.file.flush()
			except Queue.Empty:
				pass
	
	def stop(self):
		self.abort = True

log = PymineLogger()

server = server.Server(log)
server.setup()
try:
	server.listen()
except KeyboardInterrupt:
	log.info("Gracefully terminating")
	log.stop()
	server.close()
except Exception, e:
	log.error(e)
Ejemplo n.º 21
0
 async def __aexit__(self, exc_type, exc_val, exc_tb):
     for server in self.servers:
         server.close()
Ejemplo n.º 22
0
def p_server_close(p):
    """close_server : CLOSE_SERVER"""
    server.close(server_socket)