Exemplo n.º 1
0
def main():
    parser = argparse.ArgumentParser(description='Tic Tac Toe')
    subparsers = parser.add_subparsers(title='Module', dest='module')
    subparsers.required = True
    subparsers.add_parser('server', help='start the server')
    subparsers.add_parser('client', help='start a client')

    args = parser.parse_args()
    if args.module == 'server':
        server = Server()
        try:
            server.start()
        except BaseException as e:
            logger.error('Process interrupted, stopping the server', exc_info=e)
        finally:
            server.stop()
    elif args.module == 'client':
        client = Client()
        try:
            client.connect()
            client.run()
        except BaseException as e:
            logger.error('Process interrupted, disconnecting the client', exc_info=e)
        finally:
            client.disconnect()
    else:
        print('unknown type {}'.format(args.module), file=sys.stderr)
Exemplo n.º 2
0
    def handle_menu_events(self):
        """Handle Active Scene Events"""
        if self.active_scene.ref_servers_clicked:
            self.active_scene.ref_servers_clicked = False
            self.client.search_servers()

        if self.active_scene.ref_nic_clicked:
            self.active_scene.ref_nic_clicked = False
            self.active_scene.load_ip_options()

        if self.active_scene.play_clicked:
            self.active_scene.play_clicked = False
            if self.active_scene.server_selected:
                ip_addr = self.active_scene.server_selected['tcp_addr']
                self.client.tcp_connect(tuple(ip_addr))

                print('\n\n\n\n aq\n\n\n')
                self.state = INGAME
                self.active_scene = self.game_scene
            else:
                print("Cannot play: No selected server")

        if self.state == MENU:
            if self.active_scene.create_server_clicked:
                self.active_scene.create_server_clicked = False
                if self.active_scene.nic_selected:
                    ip_addr = self.active_scene.nic_selected['ip']
                    self.active_scene.ref_servers_clicked = True
                    self.server = Server(ip=ip_addr)
                    self.server.wait_conn()
                else:
                    print("Cannot create server: No IP selected")
Exemplo n.º 3
0
class ServerDialog(QDialog, Ui_ServerDialog):
    
    def startServerClicked(self):
        self.message("ServerDialog.startServerClicked - Start / threadId="+str(int(QThread.currentThreadId()))) 
        self.worker.startServer();
        
    def stopServerClicked(self):
        self.message("ServerDialog.stopServerClicked - Start / threadId="+str(int(QThread.currentThreadId()))) 
        self.worker.stopServer();
    
    @pyqtSlot('bool')   
    def setConnectionStatus(self, enabled):
        if not enabled:
            self.startServerButton.clicked.disconnect(self.stopServerClicked)
            self.startServerButton.clicked.connect(self.startServerClicked)
            self.startServerButton.setText("Start server")         
        else:
            self.startServerButton.clicked.disconnect(self.startServerClicked)
            self.startServerButton.clicked.connect(self.stopServerClicked)
            self.startServerButton.setText("Stop server")  
                            
    def message(self, str_):
        self.messageQueue.put(str_)

    def update(self):
        scrollToBottom = False;
        while self.messageQueue.empty()!=True:
            message = self.messageQueue.get()
            listItem = QListWidgetItem()
            listItem.setText(message)
            self.messageList.addItem(listItem)
            scrollToBottom = True;
            
        if scrollToBottom:
            self.messageList.scrollToBottom()
        
    def __init__(self):
        super().__init__() 
        self.messageQueue = Queue()
        
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update)
        self.timer.start(250)
        self.workerThread = WorkThread()
        self.worker=Server(self.message)
        self.worker.isConnected.connect(self.setConnectionStatus)
        self.worker.moveToThread(self.workerThread)
        self.workerThread.start(QThread.HighPriority)
        self.setupUi(self)

        self.startServerButton.clicked.connect(self.startServerClicked)

    def closeEvent(self, event):
        self.worker.stopServer()
        
        # TODO: WAIT HERE UNTIL ARE THREADS ARE DEAD
        self.accept() 
        super().closeEvent(event)
Exemplo n.º 4
0
    def __init__(self):
        super().__init__() 
        self.messageQueue = Queue()
        
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update)
        self.timer.start(250)
        self.workerThread = WorkThread()
        self.worker=Server(self.message)
        self.worker.isConnected.connect(self.setConnectionStatus)
        self.worker.moveToThread(self.workerThread)
        self.workerThread.start(QThread.HighPriority)
        self.setupUi(self)

        self.startServerButton.clicked.connect(self.startServerClicked)
Exemplo n.º 5
0
    def __init__(self, master, width=500, height=450):
        self.master = master
        self.frame = tk.Frame(self.master, width=width, height=height)
        self.print_queue = Queue()
        # setting title
        self.master.title("Server v%s" % str(version))
        # setting size
        self.frame.pack(fill="both", expand=False)
        self.frame.grid_propagate(False)
        self.frame.grid_rowconfigure(0, weight=1)
        self.frame.grid_columnconfigure(0, weight=1)
        root.maxsize(width=500, height=450)
        root.minsize(width=500, height=450)

        #button frame

        self.button_frame = tk.Frame(self.frame, width=100, height=50)

        #buttons
        self.start_button = tk.Button(self.button_frame, text="Start Server", command=self.start_server)
        self.end_button = tk.Button(self.button_frame, text="Stop Server", command=self.end_server)
        self.clear_button = tk.Button(self.button_frame, text="Clear Console", command=self.clear_log)

        #textbox
        self.text1 = tk.Text(self.frame)
        self.text1.config(state=tk.DISABLED)

        #scrollbar
        self.scrollbar = tk.Scrollbar(self.frame, command=self.text1.yview)
        self.text1['yscrollcommand'] = self.scrollbar.set

        #gridding things
        self.button_frame.grid(row=1, column=0, sticky="nsew")
        self.start_button.pack(side=tk.LEFT)
        self.end_button.pack(side=tk.LEFT)
        self.clear_button.pack(side=tk.LEFT)
        self.text1.grid(row=0, column=0, sticky="nsew")
        self.scrollbar.grid(row=0, column=1, sticky="nsw")

        self.server_address = ('172.16.0.56', 7777)
        root.after(10, self.log_print)
        root.protocol('WM_DELETE_WINDOW', self.on_destroy)

        self.server = Server(self.print_queue)
Exemplo n.º 6
0
from Server.server import Server
from Data.Binance import Binance

b = Binance("BNBBTC")
s = Server(b, stock=0, balance=1, after_trade=20)
s.run(time_to_repeat=519, delay_in_seconds=1)
Exemplo n.º 7
0
from Server.server import Server
from Handler.handler import Handler
import logging
import sys

from models.config import Config

logging.basicConfig(
    level=logging.ERROR,
    format='%(name)s: %(message)s',
    stream=sys.stderr,
)

if __name__ == '__main__':
    config = Config("/etc/httpd.conf")
    handler = Handler()
    server = Server(config.host, config.port, config, handler)
    server.start()
Exemplo n.º 8
0
from Server.server import Server

s = Server()
Exemplo n.º 9
0
class Main:
    """Main program"""
    def __init__(self):
        # "MVC" message model
        self.msg = {
            'filtered_events': [],
            'pressed_keys': [],
            'servers': [],
            'update_servers': False
        }

        # pygame statements
        pygame.init()
        pygame.display.set_caption('Pong-Lan')
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))

        # Screens Statements
        self.state = MENU
        self.font = pygame.font.Font(path.join(path.dirname(__file__), \
        "Client", "src", "bit5x3.ttf"), 12)
        self.menu = PongMenu()
        self.game_scene = GameScene()
        self.active_scene = self.menu

        # Client / Server
        self.client = Client()
        self.client.search_servers()

        self.server = None

    def process_ev_to_client(self):
        """Process events there will be sent to server, only\
    send K_UP and K_DOWN related"""
        msg = []
        for event in self.msg['filtered_events']:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    msg.append(("KEYDOWN", "K_UP"))
                elif event.key == pygame.K_DOWN:
                    msg.append(("KEYDOWN", "K_DOWN"))
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                    msg.append(("KEYUP", "K_UP"))
                elif event.key == pygame.K_DOWN:
                    msg.append(("KEYUP", "K_DOWN"))
        return msg

    def handle_client_events(self):
        """Handle Client events"""
        if self.client.updated_state:
            self.client.updated_state = False
            self.msg['servers'] = self.client.available_servers
            self.msg['update_servers'] = True

        if self.client.connected:
            self.client.handle_tcp(self.process_ev_to_client())

    def handle_menu_events(self):
        """Handle Active Scene Events"""
        if self.active_scene.ref_servers_clicked:
            self.active_scene.ref_servers_clicked = False
            self.client.search_servers()

        if self.active_scene.ref_nic_clicked:
            self.active_scene.ref_nic_clicked = False
            self.active_scene.load_ip_options()

        if self.active_scene.play_clicked:
            self.active_scene.play_clicked = False
            if self.active_scene.server_selected:
                ip_addr = self.active_scene.server_selected['tcp_addr']
                self.client.tcp_connect(tuple(ip_addr))

                print('\n\n\n\n aq\n\n\n')
                self.state = INGAME
                self.active_scene = self.game_scene
            else:
                print("Cannot play: No selected server")

        if self.state == MENU:
            if self.active_scene.create_server_clicked:
                self.active_scene.create_server_clicked = False
                if self.active_scene.nic_selected:
                    ip_addr = self.active_scene.nic_selected['ip']
                    self.active_scene.ref_servers_clicked = True
                    self.server = Server(ip=ip_addr)
                    self.server.wait_conn()
                else:
                    print("Cannot create server: No IP selected")

    def render_fps(self):
        """Render fps text on screen"""
        fps = floor(self.clock.get_fps())
        fps_text = self.font.render(str(fps), True, WHITE)
        self.screen.blit(fps_text,
                         (0, self.screen.get_height() - fps_text.get_height()))

    def run(self):
        """Run main program"""
        while True:
            self.msg['pressed_keys'] = pygame.key.get_pressed()
            self.msg['filtered_events'] = []
            for event in pygame.event.get():
                quit_attempt = False
                if event.type == pygame.QUIT:
                    quit_attempt = True
                elif event.type == pygame.KEYDOWN:
                    alt_pressed = self.msg['pressed_keys'][pygame.K_LALT] or \
                    self.msg['pressed_keys'][pygame.K_RALT]
                    if event.key == pygame.K_ESCAPE:
                        quit_attempt = True
                    elif event.key == pygame.K_F4 and alt_pressed:
                        quit_attempt = True

                if quit_attempt:
                    if self.server:
                        self.server.quit = True
                    pygame.quit()
                    sys.exit()
                else:
                    self.msg['filtered_events'].append(event)

            self.handle_client_events()
            if self.state == MENU:
                self.handle_menu_events()
            else:
                pass
            if self.state == MENU:
                self.active_scene.update(self.msg)

            self.screen.fill(BLACK)

            if self.state == MENU:
                self.active_scene.render(self.screen)
            elif self.state == INGAME:
                pad1, pad2, ball, _, _ = self.client.game_state
                self.active_scene.draw(self.screen, pad1, pad2, ball)

            self.render_fps()
            pygame.display.update()

            if self.msg['update_servers']:
                self.msg['update_servers'] = False

            self.clock.tick(60)
Exemplo n.º 10
0
from Server.server import Server

SERVER_IP = 'localhost'
SERVER_PORT = 6789
LOGFILE = "log.txt"
Server = Server(SERVER_IP, SERVER_PORT, LOGFILE)
Server.listen()
Exemplo n.º 11
0
Arquivo: main.py Projeto: karust/mlmc
        # Support pyinstaller wrapped program.
        arguments = argv[1:]
    else:
        arguments = argv
    argument_line = u' '.join(arguments)
    executable = sys.executable
    ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line,
                                None, 1)
    if int(ret) <= 32:
        return False
    return None


def runAnalyzer():
    proc = subprocess.Popen([sys.executable, "Static/analyzer.py"],
                            shell=False)
    proc.communicate()
    #shell32 = ctypes.windll.shell32
    #ret = shell32.ShellExecuteW(None, u"runas", sys.executable, "Static/analyzer.py", None, 1)


if __name__ == "__main__":
    if os.name == 'nt':
        # Should not be run at Linux
        run_as_admin()

    threading.Thread(target=runAnalyzer).start()

    server = Server(ip='127.0.0.1', port=8888)
    server.run()
Exemplo n.º 12
0
            else:
                game.start()
                break

        except:
            uiError = ' Error: Connection refused '
            uiState = -1

    elif ui.bind:  # If hosting a game
        try:
            if ui.payload[3]['boolean']:
                gamemode = 'ffa'
            elif ui.payload[4]['boolean']:
                gamemode = 'br'

            Server(
                ui.bind[0], ui.bind[1], {
                    'gamemode': gamemode,
                    'players': ui.payload[6]['value'],
                    'bullets': ui.payload[7]['value'],
                    'rockets': ui.payload[8]['value'],
                    'tickrate': ui.payload[10]['value']
                })
            break
        except:
            uiError = ' Error: Unable to bind server to given address '
            uiState = -1

s.refresh()
curses.endwin()
Exemplo n.º 13
0
from flask import Flask, request
from werkzeug.contrib.fixers import ProxyFix
import sys
from Server.server import Server
import json

#Настройка логирования
from Server.s_log import setup_logger
alice_log = setup_logger('alice logger', 'alice.log')

#импорт набора фраз
from Server.alice_client import AliceClient

#Запуск сервера
server = Server()
server.start()

# Хранилище данных о сессиях.
sessionStorage = {}

app = Flask(__name__)


@app.route('/clients')
def get_clients():
    try:
        global server
        return 'Clients:\n' + '\n'.join(server.get_client_list())
    except:
        return str(sys.exc_info())
Exemplo n.º 14
0
 def start_server(self):
     server = Server(self.port)
     server.start()
     return server