Пример #1
0
def main():
    """Main function where the control flow stars """
    port = 6667
    user = ''
    password = ''
    debug = False
    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   "u:p:w:h:d",
                                   ["user="******"port=",
                                    "password="******"help",
                                    "debug"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    if len(opts) == 0:
        usage()
        sys.exit(2)
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        if o in ("-p", "--port"):
            try:
                port = int(a)
            except:
                print "port should be an integer"
                sys.exit()
        if o in ("-u", "--user"):
            if a.find('@') < 1:
                print "user name should be in form [email protected]"
                sys.exit()
            else:
                user = a
        if o in ("-w", "--password"):
            password = a
        if o in ("-d", "--debug"):
            print "debug messages on"
            debug = True

    service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    service.bind(("", port))
    service.listen(1)

    print "listening on port", port

    (clientsocket, address ) = service.accept()
    ct = ClientThread(clientsocket, port, user, password, debug)
    ct.start()
    service.shutdown(socket.SHUT_RDWR)
Пример #2
0
    def __init__(self):
        self.clients = []  # List of clients

        # Making server socket and making it to listen for incoming data.
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind((sys.argv[1], int(sys.argv[2])))
        server.listen(5)

        #Registering function to be executed right before exiting.
        atexit.register(self.exitfunction, serversocket=server)
        while True:
            try:
                (client, address) = server.accept()  #Accepting new client
                #Looking for nickname, that is not in use yet
                ct = ClientThread(client, self)
                ct.start()
                self.clients.append(ct)
            except KeyboardInterrupt:
                break
        self.exitfunction(server)
Пример #3
0
    def __init__(self):
        self.clients = []  # List of clients

        # Making server socket and making it to listen for incoming data.
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind((sys.argv[1], int(sys.argv[2])))
        server.listen(5)

        #Registering function to be executed right before exiting.
        atexit.register(self.exitfunction, serversocket=server)
        while True:
            try:
                (client, address) = server.accept()  #Accepting new client
                #Looking for nickname, that is not in use yet
                ct = ClientThread(client, self)
                ct.start()
                self.clients.append(ct)
            except KeyboardInterrupt:
                break
        self.exitfunction(server)
Пример #4
0
            fileinfo_data = {
                'to': to,
                'filename': basename,
                'filesize': os.path.getsize(filename)
            }
            fileinfo = json.dumps({
                'type': _type,
                'msg': 0,
                'data': fileinfo_data
            })
            self.sock.send(fileinfo.encode('utf-8'))
            time.sleep(0.2)  # 防止沾包
            with open(filename, 'rb') as f:
                file_data = f.read(1024)
                while file_data:
                    self.sock.send(file_data)
                    file_data = f.read(1024)
            end_info = json.dumps({'type': _type, 'msg': 1, 'data': ''})
            self.sock.send(end_info.encode('utf-8'))  # 发送结束消息

        else:  # 文本消息
            send_msg = json.dumps({'type': _type, 'msg': msg, 'data': data})
            self.send_msg_queue.put(send_msg.encode('utf-8'))


if __name__ == '__main__':
    client = Client('127.0.0.1', 5000)
    client.connect()
    client_thread = ClientThread(client)
    client_thread.start()
Пример #5
0
import socket
from SocketServer import ThreadingMixIn
from clientthread import ClientThread
import json
#from db import insert
#from db import print_all

# Multithreaded Python server : TCP Server Socket Program Stub
TCP_IP = "127.0.0.1"
TCP_PORT = input("Port: ")

tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpServer.bind((TCP_IP, TCP_PORT))
tcpServer.listen(4)
threads = []

print "Multithreaded Python server : Waiting for connections from TCP clients..."

while True:
    (conn, addr) = tcpServer.accept()
    newthread = ClientThread(conn, addr)
    newthread.start()
    threads.append(newthread)

for t in threads:
    t.join()
Пример #6
0
 def _start_new_client_thread(self, client_socket, client_address):
     client_thread = ClientThread(client_socket, self.__db_config, self.__rabbit_config, self._ssl_enabled, self._ssl_context, client_address)
     logging.debug("Starting new client thread")
     client_thread.start()
     self.__thread_list.append(client_thread)
Пример #7
0
class GameFrame(QtGui.QFrame):
    def __init__(self, parent, width, height):
        super(GameFrame, self).__init__(parent)
        self.width = width
        self.height = height
        self.resize(self.width, self.height)

        #Input
        self.keys = {}

        #Chat
        self.chatMode = False
        self.chat = Chat(10, self.height - 210, 600, 200)

        #World (holds map size, entities, characters/players)
        self.world = World()

        #Character
        character = Character()
        character.setName("Macke")
        character.setPos(300, 300)
        self.world.setCharacter(character)

        #Server connection
        self.threadHandler = ClientThread(self.world.getCharacter(),
                                          self.world.getOtherPlayers())
        self.threadHandler.start()

    def closeEvent(self, event):
        print("closed window")

    def initFrame(self):
        self.isWaitingAfterLine = false

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        color = QtGui.QColor(0x450045)

        for e in self.world.getEntities():
            e.draw(painter)

        for op in self.world.getOtherPlayers():
            op.draw(painter)

        self.world.getCharacter().draw(painter)

        self.chat.draw(painter)

    def draw(self):
        self.repaint()

    def update(self):

        for k, v in self.keys.items():
            self.handleKeys(k, v)

        self.world.getCharacter().update()

        self.world.setOtherPlayers(self.threadHandler.getOtherPlayers())
        for e in self.world.getEntities():
            e.update()

        for op in self.world.getOtherPlayers():
            op.update()

        self.chat.update()

    def handleKeys(self, key, value):

        if key == QtCore.Qt.Key_W and not value:
            self.world.getCharacter().stopUp()

        if key == QtCore.Qt.Key_S and not value:
            self.world.getCharacter().stopDown()

        if key == QtCore.Qt.Key_A and not value:
            self.world.getCharacter().stopLeft()

        if key == QtCore.Qt.Key_D and not value:
            self.world.getCharacter().stopRight()

        if key == QtCore.Qt.Key_W and value:
            self.world.getCharacter().moveUp()

        if key == QtCore.Qt.Key_S and value:
            self.world.getCharacter().moveDown()

        if key == QtCore.Qt.Key_A and value:
            self.world.getCharacter().moveLeft()

        if key == QtCore.Qt.Key_D and value:
            self.world.getCharacter().moveRight()

    def keyReleaseEvent(self, event):
        key = event.key()
        self.keys[key] = False
        event.accept()

    def keyPressEvent(self, event):
        key = event.key()
        self.keys[key] = True
        event.accept()

        if self.chatMode and key == QtCore.Qt.Key_Return:
            m = Message(self.chat.getNewLine(),
                        self.world.getCharacter().getName())
            self.world.getCharacter().newMessage(m)
            self.chat.addMessage(m)
            self.chatMode = False
            self.chat.clearNewLine()

        if self.chatMode and key < 0x110000:
            self.chat.appendLetter(chr(key))
            return

        if key == QtCore.Qt.Key_Y:
            self.chatMode = True