コード例 #1
0
ファイル: main.py プロジェクト: 99btyler/simple-chat-room
    def __init__(self):

        self.client = Client()
        self.server = Server()

        self.print_tag = "[LAUNCHER]"

        # Tkinter root
        self.root = tk.Tk()
        self.root.title("launcher")
        self.root.resizable(False, False)
        self.root.protocol("WM_DELETE_WINDOW", self.__handle_close)

        # Tkinter frame
        self.frame = ttk.Frame(self.root)
        self.frame.grid()

        # Tkinter widgets
        self.button_launchclient = ttk.Button(
            self.frame,
            text="Client",
            padding=50,
            command=lambda: self.client.launch())
        self.button_launchclient.grid()

        self.button_launchserver = ttk.Button(
            self.frame,
            text="Server",
            padding=50,
            command=lambda: self.server.launch())
        self.button_launchserver.grid()

        # Tkinter mainloop
        self.root.mainloop()
コード例 #2
0
ファイル: clientControl.py プロジェクト: neuroph12/sew-4
class Control:
    def __init__(self, nickname="Unnamed"):
        """
        Control class used for the client

        :param nickname: Nickname to identify the client
        """
        self.view = View()
        self.model = Model(nickname)
        self.client = Client(msg_handler=self.recv)
        self.client.start()

        self.view.frame.setWindowTitle("Client - " + nickname)
        self.view.frame.onclose(self.client.close)

        QtCore.QObject.connect(self.view.frame.bsend,
                               QtCore.SIGNAL("clicked()"), self.send)

    def recv(self, msg):
        self.view.frame.chat.append(msg)

    def send(self):
        """
        Gets the message from views msgbox and sends it as the client
        """
        msg = self.view.frame.msgbox.text()
        self.client.send(self.model.nickname + ": " + msg)
        self.view.frame.chat.append(msg)
        self.view.frame.msgbox.clear()
コード例 #3
0
ファイル: clientControl.py プロジェクト: neuroph12/sew-4
    def __init__(self, nickname="Unnamed"):
        """
        Control class used for the client

        :param nickname: Nickname to identify the client
        """
        self.view = View()
        self.model = Model(nickname)
        self.client = Client(msg_handler=self.recv)
        self.client.start()

        self.view.frame.setWindowTitle("Client - " + nickname)
        self.view.frame.onclose(self.client.close)

        QtCore.QObject.connect(self.view.frame.bsend,
                               QtCore.SIGNAL("clicked()"), self.send)
コード例 #4
0
    def init_client(self):
        roomLabel = QtGui.QLabel('AB2014')

        self.browser = QtGui.QTextBrowser()

        self.textEdit = QtGui.QTextEdit()
        self.textEdit.setMaximumSize(QtCore.QSize(500, 60))
        self.connect(self.textEdit, QtCore.SIGNAL("returnPressed()"),
                     self.callback)

        self.sendButton = QtGui.QPushButton('Send')
        self.sendButton.setMaximumSize(QtCore.QSize(500, 60))
        self.sendButton.clicked.connect(self.callback)

        layoutINlayout = QtGui.QHBoxLayout()
        layoutINlayout.addWidget(self.textEdit)
        layoutINlayout.addWidget(self.sendButton)

        widget = QtGui.QWidget()
        self.setCentralWidget(widget)

        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.browser)

        mainwindow = QtGui.QVBoxLayout()
        mainwindow.addLayout(self.layout)
        mainwindow.addLayout(layoutINlayout)

        widget.setLayout(mainwindow)

        self.setWindowTitle("AB2014 Chat Client")
        self.setGeometry(200, 200, 600, 600)
        self.show()

        self.get_connection_parameters()
        self.client = Client(self.hostname, self.port)

        self.client.start()
        QtCore.QObject.connect(self.client, QtCore.SIGNAL('message_received'),
                               self.show_message)
        QtCore.QObject.connect(self.client,
                               QtCore.SIGNAL('message_received_from_server'),
                               self.show_server_message)

        self.client.send_username(str(self.username))
        self.statusBar().showMessage('Connected to {0}:{1} as {2}'.format(
            self.hostname, self.port, self.username))
コード例 #5
0
ファイル: client.py プロジェクト: farukuzun/ab-python-2014
    def init_client(self):
        roomLabel = QtGui.QLabel('AB2014')

        self.browser = QtGui.QTextBrowser()

        self.textEdit = QtGui.QTextEdit()
        self.textEdit.setMaximumSize(QtCore.QSize(500,60))
        self.connect(self.textEdit, QtCore.SIGNAL("returnPressed()"),self.callback)

        self.sendButton = QtGui.QPushButton('Send')
        self.sendButton.setMaximumSize(QtCore.QSize(500,60))
        self.sendButton.clicked.connect(self.callback)

        layoutINlayout = QtGui.QHBoxLayout()
        layoutINlayout.addWidget(self.textEdit)
        layoutINlayout.addWidget(self.sendButton)


        widget = QtGui.QWidget()
        self.setCentralWidget(widget)

        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.browser)

        mainwindow = QtGui.QVBoxLayout()
        mainwindow.addLayout (self.layout )
        mainwindow.addLayout (layoutINlayout )

        widget.setLayout(mainwindow)

        self.setWindowTitle("AB2014 Chat Client")
        self.setGeometry(200, 200, 600, 600)
        self.show()

        self.get_connection_parameters()
        self.client = Client(self.hostname, self.port)

        self.client.start()
        QtCore.QObject.connect(self.client, QtCore.SIGNAL('message_received'), self.show_message)
        QtCore.QObject.connect(self.client, QtCore.SIGNAL('message_received_from_server'), self.show_server_message)

        self.client.send_username(str(self.username))
        self.statusBar().showMessage('Connected to {0}:{1} as {2}'.format(self.hostname, self.port, self.username))
コード例 #6
0
ファイル: client.py プロジェクト: farukuzun/ab-python-2014
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.init_client()

    def init_client(self):
        roomLabel = QtGui.QLabel('AB2014')

        self.browser = QtGui.QTextBrowser()

        self.textEdit = QtGui.QTextEdit()
        self.textEdit.setMaximumSize(QtCore.QSize(500,60))
        self.connect(self.textEdit, QtCore.SIGNAL("returnPressed()"),self.callback)

        self.sendButton = QtGui.QPushButton('Send')
        self.sendButton.setMaximumSize(QtCore.QSize(500,60))
        self.sendButton.clicked.connect(self.callback)

        layoutINlayout = QtGui.QHBoxLayout()
        layoutINlayout.addWidget(self.textEdit)
        layoutINlayout.addWidget(self.sendButton)


        widget = QtGui.QWidget()
        self.setCentralWidget(widget)

        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.browser)

        mainwindow = QtGui.QVBoxLayout()
        mainwindow.addLayout (self.layout )
        mainwindow.addLayout (layoutINlayout )

        widget.setLayout(mainwindow)

        self.setWindowTitle("AB2014 Chat Client")
        self.setGeometry(200, 200, 600, 600)
        self.show()

        self.get_connection_parameters()
        self.client = Client(self.hostname, self.port)

        self.client.start()
        QtCore.QObject.connect(self.client, QtCore.SIGNAL('message_received'), self.show_message)
        QtCore.QObject.connect(self.client, QtCore.SIGNAL('message_received_from_server'), self.show_server_message)

        self.client.send_username(str(self.username))
        self.statusBar().showMessage('Connected to {0}:{1} as {2}'.format(self.hostname, self.port, self.username))


    def get_connection_parameters(self):
        text, username_ok = QtGui.QInputDialog.getText(self, 'username', 'Enter user name:')
        if username_ok:
            self.username = text
        else:
            QtCore.QCoreApplication.instance().quit

        text, hostname_ok = QtGui.QInputDialog.getText(self, 'Hostname', 'Enter host name:')
        if hostname_ok:
            self.hostname = text
        else:
            QtCore.QCoreApplication.instance().quit

        text, port_ok = QtGui.QInputDialog.getText(self, 'Port', 'Enter port number:')
        if port_ok:
            self.port = int(text)
        else:
            QtCore.QCoreApplication.instance().quit

        if self.username == None or self.hostname == None or self.port == None:
            QtCore.QCoreApplication.instance().quit


    def closeEvent(self, event):

        reply = QtGui.QMessageBox.question(self, 'Message',
            "Are you sure to quit?", QtGui.QMessageBox.Yes |
            QtGui.QMessageBox.No, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def callback(self, event):
        message = unicode(self.textEdit.toPlainText())
        self.client.send(message)

    def show_message(self, data):
        self.browser.insertHtml(QtCore.QString("<span style=\" color:#00ff00;\">%1</span><br>").arg(data))

    def show_server_message(self, data):
        self.browser.insertHtml(QtCore.QString("<span style=\" color:#ff0000;\">%1</span><br>").arg(data))
コード例 #7
0
def request_handler(client_socket, addr):

    global messages_cache

    now = int(time.time())
    client = Client(client_socket)
    client_manager.add_client(client)

    client_manager.lose_time_out_clients(now)

    print_log('[%s]' % get_datetime_str(), 'connected from %s:%s' % addr,
              'client_socked_fd:', client.fileno)
    print_log('clients_num :', client_manager.get_client_count())

    while True:
        try:
            data = client_socket.recv(BUFFSIZE)
        except:
            client_manager.lose_client(client)
            break

        if not data:
            print_log('[%s]' % get_datetime_str(),
                      'client %s:%s disconnected' % addr,
                      'flag: %s, %s' % (data, type(data)))
            client_manager.lose_client(client)
            print_log('clients_num :', client_manager.get_client_count())
            break

        if data.strip().lower() == 'check':
            now = int(time.time())
            client_socket.sendall(str(process.get_memory_info()) + '|')
            client_socket.sendall('\nclients_num : %s;' %
                                  client_manager.get_client_count())
            client_socket.sendall(
                '\nper_client_connect_time: "[(fileno, uid, game_id, '
                'guild_id, server_name, vip, domain, team_id, live_time)]--> %s";'
                % str(
                    sorted([(x, y.uid, y.game_id, y.guild_id, y.server_name,
                             y.vip, y.domain, y.team_id, now - y.ttl)
                            for x, y in client_manager._clients.iteritems()],
                           key=lambda x: x[1],
                           reverse=True)))
            client_socket.sendall('\n')
            continue

        if data.strip().lower() == 'check_contents':
            client_socket.sendall(
                str(process.get_memory_info()) + '|' +
                str(id(content_factory)))
            client_socket.sendall('\ncontents : %s;' % repr([
                content.__dict__
                for content in content_factory._contents.itervalues()
            ]))
            client_socket.sendall('\n')
            continue

        if data.strip().lower() == 'quit':
            client_manager.lose_client(client)
            break

        # buffer超了指定大小还未找到规定格式的数据,主动断开连接
        if len(client.buffer) >= MAX_BUFFER_SIZE:
            client_manager.lose_client(client)
            break

        info = client.parse(data)

        if not info:
            continue

        tp = info['kqgFlag']
        if tp == 'first':
            try:
                u = User.get(info.get('uid'))
            except:
                client_manager.lose_client(client)
                break

            # if u.session_expired(info.get('ks')) or (u.device_mark and u.device_mark != info.get('device_mark'))\
            #         or (u.device_mem and u.device_mem != info.get('device_mem')):
            #     client_manager.lose_client(client)
            #     continue

            if u.is_ban:
                client_manager.lose_client(client)
                break

            client.init_info(info.get('uid'), info.get('association_id', ''),
                             info.get('game_id', ''), info.get('vip', 0),
                             info.get('domain', ''), info.get('team_id', ''),
                             addr[0], info.get('sid'), info.get('device_mark'),
                             info.get('device_mem'))

            client_manager.add_server_client(client)
            # if client.vip >= 8:
            #     receivers_vip = []
            #     for _fd, _client in client_manager.get_client_by_server_name(client.server_name).items():
            #         if _fd != client.fileno:
            #             receivers_vip.append(gevent.spawn(_client.socket.sendall, client.msg))
            #     gevent.joinall(receivers_vip)
            #
            #     content = content_factory.get(content_factory.MAPPINGS['world'], client.server_name)
            #     content.add(client.msg)
            if GAG_MSG_SWITCH:
                client.socket.sendall(force_str(get_default_msg()))

            if not GAG_MSG_SWITCH:
                content = content_factory.get(
                    content_factory.MAPPINGS['world'], client.server_name)
                msgs = content.show()
                if msgs:
                    client.socket.sendall(''.join(msgs))

                content_friend = content_factory.get(
                    content_factory.MAPPINGS['friend'], client.server_name,
                    client.uid)
                msgs = content_friend.get(client.uid)
                content_factory.delete(content_factory.MAPPINGS['friend'],
                                       client.server_name, client.uid)
                if msgs:
                    client.socket.sendall(''.join(msgs))

                client_manager.lose_repeat_clients(client)
            continue

        if tp == 'update':
            client.update_info(info.get('association_id'), info.get('domain'),
                               info.get('team_id'))

        if GAG_MSG_SWITCH:
            continue

        if client.uid in GAG_UIDS:
            continue

        u = User.get(client.uid)
        if not settings.SESSION_SWITCH and u.ip and u.ip != client.ip:
            continue

        if settings.SESSION_SWITCH and (
                u.session_expired(info.get('ks')) or
            (u.device_mark and u.device_mark != info.get('device_mark')) or
            (u.device_mem and u.device_mem != info.get('device_mem'))):
            continue

        if u.is_ban:
            continue

        next_flag = info.get('next')
        if next_flag and tp in ['world', 'system', 'guild'
                                ] and next_flag in [1, 2]:
            content = content_factory.get(content_factory.MAPPINGS[tp],
                                          client.server_name)
            msgs = content.show(next_flag)
            if msgs:
                client.socket.sendall(''.join(msgs))
            continue

        con_name = content_factory.MAPPINGS.get(tp)
        if con_name and tp not in content_factory.IGNORE:
            content = content_factory.get(con_name, client.server_name)
            content.add(client.msg)

        sendToUid = info.get('sendToUid', '')
        receivers = []
        for _fd, _client in client_manager.get_client_by_server_name(
                client.server_name).iteritems():
            if _fd == client.fileno:
                continue
            # 判断消息是否需要发送  用gevent.spawn 处理
            if tp in ['world', 'system']:  # 世界, 系统
                receivers.append(
                    gevent.spawn(_client.socket.sendall, _client.msg))
            elif tp == 'guild':  # 公会
                if _client.guild_id and _client.guild_id == client.guild_id:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))
            elif tp == 'friend' and _client.uid == sendToUid:  # 好友
                receivers.append(
                    gevent.spawn(_client.socket.sendall, client.msg))
                break
            elif tp == 'guild_war':  # 工会战
                if _client.guild_id and client.guild_id:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))
            elif tp in ['rob', 'escort']:  # 运镖, 打劫
                if client.domain and client.domain == _client.domain:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))
            elif tp == 'team':  # 队伍
                if client.team_id and client.team_id == _client.team_id:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))

        # 私聊缓存
        if tp == 'friend' and sendToUid and not receivers:
            content = content_factory.get(content_factory.MAPPINGS[tp],
                                          client.server_name, sendToUid)
            content.add(client.msg)
            # content.save()

        gevent.joinall(receivers)
コード例 #8
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.init_client()

    def init_client(self):
        roomLabel = QtGui.QLabel('AB2014')

        self.browser = QtGui.QTextBrowser()

        self.textEdit = QtGui.QTextEdit()
        self.textEdit.setMaximumSize(QtCore.QSize(500, 60))
        self.connect(self.textEdit, QtCore.SIGNAL("returnPressed()"),
                     self.callback)

        self.sendButton = QtGui.QPushButton('Send')
        self.sendButton.setMaximumSize(QtCore.QSize(500, 60))
        self.sendButton.clicked.connect(self.callback)

        layoutINlayout = QtGui.QHBoxLayout()
        layoutINlayout.addWidget(self.textEdit)
        layoutINlayout.addWidget(self.sendButton)

        widget = QtGui.QWidget()
        self.setCentralWidget(widget)

        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.browser)

        mainwindow = QtGui.QVBoxLayout()
        mainwindow.addLayout(self.layout)
        mainwindow.addLayout(layoutINlayout)

        widget.setLayout(mainwindow)

        self.setWindowTitle("AB2014 Chat Client")
        self.setGeometry(200, 200, 600, 600)
        self.show()

        self.get_connection_parameters()
        self.client = Client(self.hostname, self.port)

        self.client.start()
        QtCore.QObject.connect(self.client, QtCore.SIGNAL('message_received'),
                               self.show_message)
        QtCore.QObject.connect(self.client,
                               QtCore.SIGNAL('message_received_from_server'),
                               self.show_server_message)

        self.client.send_username(str(self.username))
        self.statusBar().showMessage('Connected to {0}:{1} as {2}'.format(
            self.hostname, self.port, self.username))

    def get_connection_parameters(self):
        text, username_ok = QtGui.QInputDialog.getText(self, 'username',
                                                       'Enter user name:')
        if username_ok:
            self.username = text
        else:
            QtCore.QCoreApplication.instance().quit

        text, hostname_ok = QtGui.QInputDialog.getText(self, 'Hostname',
                                                       'Enter host name:')
        if hostname_ok:
            self.hostname = text
        else:
            QtCore.QCoreApplication.instance().quit

        text, port_ok = QtGui.QInputDialog.getText(self, 'Port',
                                                   'Enter port number:')
        if port_ok:
            self.port = int(text)
        else:
            QtCore.QCoreApplication.instance().quit

        if self.username == None or self.hostname == None or self.port == None:
            QtCore.QCoreApplication.instance().quit

    def closeEvent(self, event):

        reply = QtGui.QMessageBox.question(
            self, 'Message', "Are you sure to quit?",
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def callback(self, event):
        message = unicode(self.textEdit.toPlainText())
        self.client.send(message)

    def show_message(self, data):
        self.browser.insertHtml(
            QtCore.QString(
                "<span style=\" color:#00ff00;\">%1</span><br>").arg(data))

    def show_server_message(self, data):
        self.browser.insertHtml(
            QtCore.QString(
                "<span style=\" color:#ff0000;\">%1</span><br>").arg(data))