Пример #1
0
 def clientLink(self, client_socket, client_addr):
     print 'Accept new connection from %s:%s....' % client_addr
     time.sleep(1)
     to_user, from_user, data_type, data = pt.recv(client_socket)
     user_id = from_user
     user_pwd = data
     user_sever = '0:server'
     if to_user != pt.SERV_USER or data_type != pt.MSG_LOGON or data is None or not data:
         text = 'Logon Error !'
         print text
     else:
         sg = self.logon(user_id, user_pwd, client_socket, client_addr)
         if sg is None:
             user_id = self.register(client_socket, client_addr, user_id)
             if user_id is not None:
                 self.set_useronline_flag(user_id, not pt.FLAG_ONLINE)
             client_socket.close()
             print 'Close connection from %s:%s....' % client_addr
             return
         elif sg is False:
             client_socket.close()
             print 'Close connection from %s:%s....' % client_addr
             return
         user = '******'.format(user_id, self.get_user_name(
             user_id))  # %user_id   self.get_user_name(user_id)
         send_text = '[{0}] Welcome {1}'.format(user_sever, user)
         pt.send(client_socket, user_id, pt.SERV_USER, pt.MSG_LOGON,
                 send_text)
         print send_text
         while True:
             to_user, from_user, msg_type, msg = pt.recv(client_socket)
             fuser = '******'.format(from_user,
                                      self.get_user_name(from_user))
             # no the to_user
             if to_user != pt.SERV_USER and to_user not in self.get_users():
                 erro_string = '[from {0} to {1} ] {2} not regist !'.format(
                     user_sever, fuser, to_user)
                 pt.send(client_socket, from_user, pt.SERV_USER,
                         pt.MSG_TEXT, erro_string)
                 print erro_string
             # to the server ,should cmd
             elif to_user == pt.SERV_USER:
                 sg = self.process_cmd(from_user, msg)
                 if sg == pt.MSG_QUIT:
                     break
                 elif sg == pt.MSG_ERROR:
                     erro_string = '[from {0} to {1}] {2} : {3}'.format(
                         user_sever, fuser, msg, 'Wrong Cmd to Server !')
                     pt.send(client_socket, from_user, pt.SERV_USER,
                             pt.MSG_ERROR, erro_string)
                     print erro_string
             # to other client
             else:
                 sg = self.process_chat(from_user, to_user, msg)
                 if sg == pt.MSG_ERROR:
                     erro_string = '[from {0} to {1}] {2} not online !'.format(
                         user_sever, fuser, to_user)
     client_socket.close()
     print 'Close connection from %s:%s....' % client_addr
Пример #2
0
    def register(self, client_socket, client_addr, user_id):
        text = 'You have to register first ! Are you Register ?(y/n):'
        pt.send(client_socket, user_id, pt.SERV_USER, pt.MSG_REGISTER, text)
        while True:
            to_user, from_user, data_type, data = pt.recv(client_socket)
            if data.strip() != '':
                break
        if data_type != pt.MSG_REGISTER:
            return None
        elif data != 'y' and data != 'yes':
            pt.send(client_socket, user_id, pt.SERV_USER, pt.MSG_ERROR, "")
            return None
        else:
            text = 'Please input your : user_id(must Integer) user_name user_pwd \n'
            print text
            pt.send(client_socket, from_user, pt.SERV_USER, pt.MSG_REGISTER,
                    text)
            to_user, from_user, data_type, data = pt.recv(client_socket)
            dtlist = data.strip().split(' ')
            text = 'Input is Wrong !'
            if len(dtlist) != 3:
                pt.send(client_socket, from_user, pt.SERV_USER, pt.MSG_ERROR,
                        text)
                return None
            else:
                user_id = 0
                try:
                    user_id = int(dtlist[0])
                    user_name = dtlist[1]
                    user_pwd = dtlist[2]
                except:
                    text = 'UserId is Wrong !'
                    pt.send(client_socket, from_user, pt.SERV_USER,
                            pt.MSG_ERROR, text)
                    return None

                if user_id in self.get_users():
                    text = 'UserId exist !'
                    pt.send(client_socket, from_user, pt.SERV_USER,
                            pt.MSG_ERROR, text)
                    return None
                if self.get_user_id(user_name) is not None:
                    text = 'UserName exist !'
                    pt.send(client_socket, from_user, pt.SERV_USER,
                            pt.MSG_ERROR, text)
                    return None
                if self.register_user(user_id, user_name, user_pwd,
                                      client_socket, client_addr) == True:
                    text = '[from server] {0}:{1} Register OK ! PassWord : {2}'.format(
                        user_id, user_name, user_pwd)
                    pt.send(client_socket, user_id, pt.SERV_USER, pt.MSG_LOGON,
                            text)
                    self.save_users(self.__file_name)
                    return user_id
                else:
                    text = 'Register  Wrong!'
                    pt.send(client_socket, from_user, pt.SERV_USER,
                            pt.MSG_ERROR, text)
Пример #3
0
 def clientLink(self, client_socket, client_addr):
     print 'Accept new connection from %s:%s....' % client_addr
     time.sleep(1)
     to_user, from_user, data_type, data = pt.recv(client_socket)
     user_id = from_user
     user_pwd = data
     user_sever = '0:server'
     if to_user != pt.SERV_USER or data_type != pt.MSG_LOGON or data is None or not data:
         text = 'Logon Error !'
         print text
     else:
         sg = self.logon(user_id, user_pwd, client_socket, client_addr)
         if sg is None:
             user_id = self.register(client_socket, client_addr, user_id)
             if user_id is not None:
                 self.set_useronline_flag(user_id, not pt.FLAG_ONLINE)
             client_socket.close()
             print 'Close connection from %s:%s....' % client_addr
             return
         elif sg is False:
             client_socket.close()
             print 'Close connection from %s:%s....' % client_addr
             return
         user = '******'.format(user_id, self.get_user_name(user_id))  # %user_id   self.get_user_name(user_id)
         send_text = '[{0}] Welcome {1}'.format(user_sever, user)
         pt.send(client_socket, user_id, pt.SERV_USER, pt.MSG_LOGON, send_text)
         print send_text
         while True:
             to_user, from_user, msg_type, msg = pt.recv(client_socket)
             fuser = '******'.format(from_user, self.get_user_name(from_user))
             # no the to_user
             if to_user != pt.SERV_USER and to_user not in self.get_users():
                 erro_string = '[from {0} to {1} ] {2} not regist !'.format(user_sever, fuser, to_user)
                 pt.send(client_socket, from_user, pt.SERV_USER, pt.MSG_TEXT, erro_string)
                 print erro_string
             # to the server ,should cmd
             elif to_user == pt.SERV_USER:
                 sg = self.process_cmd(from_user, msg)
                 if sg == pt.MSG_QUIT:
                     break
                 elif sg == pt.MSG_ERROR:
                     erro_string = '[from {0} to {1}] {2} : {3}'.format(user_sever,
                                                                        fuser,
                                                                        msg,
                                                                        'Wrong Cmd to Server !')
                     pt.send(client_socket, from_user, pt.SERV_USER, pt.MSG_ERROR, erro_string)
                     print erro_string
             # to other client
             else:
                 sg = self.process_chat(from_user, to_user, msg)
                 if sg == pt.MSG_ERROR:
                     erro_string = '[from {0} to {1}] {2} not online !'.format(user_sever,
                                                                               fuser,
                                                                               to_user)
     client_socket.close()
     print 'Close connection from %s:%s....' % client_addr
Пример #4
0
    def register(self, client_socket, client_addr, user_id):
        text = 'You have to register first ! Are you Register ?(y/n):'
        pt.send(client_socket, user_id, pt.SERV_USER, pt.MSG_REGISTER, text)
        while True:
            to_user, from_user, data_type, data = pt.recv(client_socket)
            if data.strip() != '':
                break
        if data_type != pt.MSG_REGISTER:
            return None
        elif data != 'y' and data != 'yes':
            pt.send(client_socket, user_id, pt.SERV_USER, pt.MSG_ERROR, "")
            return None
        else:
            text = 'Please input your : user_id(must Integer) user_name user_pwd \n'
            print text
            pt.send(client_socket, from_user, pt.SERV_USER, pt.MSG_REGISTER, text)
            to_user, from_user, data_type, data = pt.recv(client_socket)
            dtlist = data.strip().split(' ')
            text = 'Input is Wrong !'
            if len(dtlist) != 3:
                pt.send(client_socket, from_user, pt.SERV_USER, pt.MSG_ERROR, text)
                return None
            else:
                user_id = 0
                try:
                    user_id = int(dtlist[0])
                    user_name = dtlist[1]
                    user_pwd = dtlist[2]
                except:
                    text = 'UserId is Wrong !'
                    pt.send(client_socket, from_user, pt.SERV_USER, pt.MSG_ERROR, text)
                    return None

                if user_id in self.get_users():
                    text = 'UserId exist !'
                    pt.send(client_socket, from_user, pt.SERV_USER, pt.MSG_ERROR, text)
                    return None
                if self.get_user_id(user_name)is not None:
                    text = 'UserName exist !'
                    pt.send(client_socket, from_user, pt.SERV_USER, pt.MSG_ERROR, text)
                    return None
                if self.register_user(user_id, user_name, user_pwd, client_socket, client_addr) == True:
                    text = '[from server] {0}:{1} Register OK ! PassWord : {2}'.format(user_id,
                                                                                       user_name,
                                                                                       user_pwd)
                    pt.send(client_socket, user_id, pt.SERV_USER, pt.MSG_LOGON, text)
                    self.save_users(self.__file_name)
                    return user_id
                else:
                    text = 'Register  Wrong!'
                    pt.send(client_socket, from_user, pt.SERV_USER, pt.MSG_ERROR, text)
Пример #5
0
def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        server_socket.bind((IP, PORT))
        server_socket.listen(QUEUE_SIZE)
        # endless loop to receive client after client
        while True:
            comm_socket, client_address = server_socket.accept()
            while True:
                try:
                    request = protocol.recv(comm_socket)
                    if request[0] == "Exit":
                        comm_socket.close()
                        break
                    # add request to answer function call
                    is_work = protocol.send(comm_socket, request)
                    if not is_work:
                        comm_socket.close()
                        break
                except socket.error as msg:
                    print 'client socket disconnected- ' + str(msg)
                    comm_socket.close()
                    break
    except socket.error as msg:
        print 'failed to open server socket - ' + str(msg)
    finally:
        server_socket.close()
Пример #6
0
 def serve_forever(self):
     self.looping = True
     while self.looping:
         input_ready, output_ready, except_ready = select.select(
             [self.unconnected_socket] + self.connected_sockets, [], [])
         for sock in input_ready:
             if sock == self.unconnected_socket:
                 #init socket
                 connected_socket, address = sock.accept()
                 self.connected_sockets.append(connected_socket)
                 self.socketaddresses[connected_socket] = address
                 self.client_connect_func(connected_socket, self.host,
                                          self.port, address)
             else:
                 try:
                     data = protocol.recv(sock)
                     address = self.socketaddresses[sock]
                     self.input_func(sock, self.host, self.port, address)
                 except:
                     data = b"client quit"
                 if data:
                     if data == b"client quit":
                         self.remove_socket(sock)
                     else:
                         self.sending_socket = sock
                         self.handle_data(data)
Пример #7
0
 def logon(self, user_id, user_pwd):
     pt.send(self.client_socket, pt.SERV_USER,
             user_id, pt.MSG_LOGON, user_pwd)
     to_user, from_user, msg_type, msg = pt.recv(self.client_socket)
     print msg
     if msg_type == pt.MSG_LOGON:
         return True
     elif msg_type == pt.MSG_ERROR:
         return False
     elif msg_type == pt.MSG_REGISTER:
         while msg_type == pt.MSG_REGISTER:
             msg = sys.stdin.readline().strip()
             pt.send(self.client_socket, pt.SERV_USER,
                     user_id, pt.MSG_REGISTER, msg)
             to_user, from_user, msg_type, msg = pt.recv(self.client_socket)
             print msg
             if msg_type == pt.MSG_LOGON:
                 return None
     return False
Пример #8
0
 def logon(self, user_id, user_pwd):
     pt.send(self.client_socket, pt.SERV_USER, user_id, pt.MSG_LOGON,
             user_pwd)
     to_user, from_user, msg_type, msg = pt.recv(self.client_socket)
     print msg
     if msg_type == pt.MSG_LOGON:
         return True
     elif msg_type == pt.MSG_ERROR:
         return False
     elif msg_type == pt.MSG_REGISTER:
         while msg_type == pt.MSG_REGISTER:
             msg = sys.stdin.readline().strip()
             pt.send(self.client_socket, pt.SERV_USER, user_id,
                     pt.MSG_REGISTER, msg)
             to_user, from_user, msg_type, msg = pt.recv(self.client_socket)
             print msg
             if msg_type == pt.MSG_LOGON:
                 return None
     return False
Пример #9
0
    def client_process(self, sock, active_clients):
        while 1:
            data = protocol.recv(sock)
            if not data:
                return sock.close()

            encryption = TripleDESCipher(data["key"])
            if data["encryption"] == 1:
                protocol.send(sock, (active_clients, encryption.encrypt(data["message"])))
            else:
                protocol.send(sock, (active_clients, encryption.decrypt(data["message"])))
Пример #10
0
def client_process(sock, server_sock, nclients, timeout=60):
    server_sock.close()
    sock.settimeout(timeout)
    while 1:
        data = protocol.recv(sock)
        if not data:
            return sock.close()

        encryption = TripleDESCipher(data["key"])
        if data["encryption"] == 1:
            protocol.send(sock, (nclients.value, encryption.encrypt(data["message"])))
        else:
            protocol.send(sock, (nclients.value, encryption.decrypt(data["message"])))
Пример #11
0
    def commitwithserver(self, input):

        prostdin = processstdin(self)
        prostdin.start()

        sign = True
        while sign:
            to_user, from_user, msg_type, msg = pt.recv(self.client_socket)
            try:
                if msg_type == pt.MSG_QUIT:
                    prostdin.done = True
                    return
                elif msg_type == pt.MSG_CMD:
                    self.curchatuser = to_user
                elif msg_type == pt.MSG_FRIEND_QUIT:
                    self.curchatuser = pt.SERV_USER
            finally:
                print msg
Пример #12
0
    def commitwithserver(self, input):

        prostdin = processstdin(self)
        prostdin.start()

        sign = True
        while sign:
            to_user, from_user, msg_type, msg = pt.recv(self.client_socket)
            try:
                if msg_type == pt.MSG_QUIT:
                    prostdin.done = True
                    return
                elif msg_type == pt.MSG_CMD:
                    self.curchatuser = to_user
                elif msg_type == pt.MSG_FRIEND_QUIT:
                    self.curchatuser = pt.SERV_USER
            finally:
                print msg
Пример #13
0
def main():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        client_socket.connect((SERVER_IP, SERVER_PORT))
        # send the message
        while True:
            massage = []
            massage.append(raw_input("enter action"))
            massage.append(raw_input("enter action"))
            protocol.send(client_socket, massage)
            if massage[0] == "Exit":
                break
            packet = []
            packet = protocol.recv(client_socket)
            print packet[0] + " " + packet[1]
    except socket.error as msg:
        print 'error in communication with server - ' + str(msg)
    finally:
        client_socket.close()
Пример #14
0
	def serve_forever(self):
		self.looping = True
		while self.looping:
			input_ready, output_ready, except_ready = select.select([self.unconnected_socket]+self.connected_sockets,[],[])
			for sock in input_ready:
				if sock == self.unconnected_socket:
					#init socket
					connected_socket, address = sock.accept()
					self.connected_sockets.append(connected_socket)
					self.socketaddresses[connected_socket] = address
					self.client_connect_func(connected_socket, self.host, self.port, address)
				else:
					try:
						data = protocol.recv(sock)
						address = self.socketaddresses[sock]
						self.input_func(sock, self.host, self.port, address)
					except:
						data = b"client quit"
					if data:
						if data == b"client quit":
							self.remove_socket(sock)
						else:
							self.sending_socket = sock
							self.handle_data(data)
Пример #15
0
# -*- coding: utf-8 -*-
# !/usr/bin/env python3

import socket

import config
import protocol


sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((config.host, config.port))
protocol.send(sock, input())
data = protocol.recv(sock)
sock.close()
print(data)
Пример #16
0
    def update(self, switch_state: Callable) -> None:
        read, write, error = select.select([self.socket], [self.socket],
                                           [self.socket], 0)

        if self.waiting:
            self.gameplay1.cancel_input.update()

            if self.socket in read:
                buffer = self.socket.recv(BUFFER_SIZE)
                if buffer == b"go":
                    self.waiting = False
                    self.current_popup2 = None
                elif buffer == b"ping":
                    self.socket.sendall(b"pong")
                elif buffer == b"":
                    print("server disconnected")
                    self.finished = True
            elif self.gameplay1.cancel:
                self.socket.close()
                self.finished = True

            return

        if not self.end_screen:
            if self.gameplay1.game_over and not self.gameplay2.game_over:
                self.gameplay2.game_over = True
                self.end_screen = True
                self.popups1.append(
                    Popup("You lost!", color="red", gcolor="orange"))
                self.popups2.append(
                    Popup("You won!", color="green", gcolor="yellow"))
            elif self.gameplay2.game_over and not self.gameplay1.game_over:
                self.gameplay1.game_over = True
                self.end_screen = True
                self.popups1.append(
                    Popup("You won!", color="green", gcolor="yellow"))
                self.popups2.append(
                    Popup("You lost!", color="red", gcolor="orange"))
            elif self.gameplay1.game_over and self.gameplay2.game_over:
                self.end_screen = True
                self.popups1.append(Popup("Draw!", color="cyan"))
                self.popups2.append(Popup("Draw!", color="cyan"))

        if self.gameplay1.cancel:
            self.gameplay1.send = True

            self.gameplay1.cancel = False
            self.gameplay1.game_over = True

            if self.end_screen or self.gameplay1.countdown > 0:
                self.finished = True

        self.gameplay1.update()

        if self.socket in read:
            try:
                self.gameplay2 = jsonpickle.decode(
                    protocol.recv(self.socket).decode())
            except (RuntimeError, ConnectionResetError):
                error = [self.socket]

        if self.socket in write and self.gameplay1.send:
            self.gameplay1.send = False
            try:
                protocol.send(self.socket,
                              jsonpickle.encode(self.gameplay1).encode())
            except (ConnectionResetError, ConnectionAbortedError):
                error = [self.socket]

        if self.socket in error:
            if not self.end_screen:
                print("communication error")
                self.finished = True

        if self.gameplay2.score.duel_lines > 0:
            hole = randint(0, 9)
            self.gameplay1.add_garbage(hole, self.gameplay2.score.duel_lines)
            self.gameplay2.score.duel_lines = 0

        self.gameplay1.score.duel_lines = 0

        self.popups1.extend(self.gameplay1.get_popups())
        self.gameplay1.clear_popups()

        self.popups2.extend(self.gameplay2.get_popups())
        self.gameplay2.clear_popups()

        if not self.current_popup1 and self.popups1:
            self.current_popup1 = self.popups1.pop(0)
        elif self.current_popup1:
            if not self.current_popup1.update():
                self.current_popup1 = None

        if not self.current_popup2 and self.popups2:
            self.current_popup2 = self.popups2.pop(0)
        elif self.current_popup2:
            if not self.current_popup2.update():
                self.current_popup2 = None
Пример #17
0
 def recv(self):
     return protocol.recv(self.sock)
Пример #18
0
            if folder_found:
                site_string += "\n================================================================================\n"
            site_string += "List of archives:\n" + "\n".join(archive_list)
        if site_string == "":
            site_string = "Sites not found!"
        protocol.send(connection, site_string)
    elif command == "load":
        load = ""
        for i in range (1, 100000):
            load += str(i) + ' '
            if i % 1000 == 0:
                load += '\n'
        protocol.send(connection, load)
    else:
        protocol.send(connection, "Invalid request")


def args_analysis(connection, args):
    args = args.split()
    handle_commands(connection=connection, command=args[0], params=args[1:])


sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((config.host, config.port))
sock.listen(True)
while True:
    conn, addr = sock.accept()
    print('Connected by ', addr)
    data = protocol.recv(conn)
    args_analysis(connection=conn, args=data)
Пример #19
0
import protocol as pv
import sys

if __name__ == "__main__":
    proto_handler = pv.socket()
    pv.connect_to(proto_handler, 'localhost', int(sys.argv[1]))

    # pv.send(proto_handler, 'connect')

    val = pv.recv(proto_handler)
    print(val)

    val += ' - no, you!'
    pv.send(proto_handler, val)
    val_new = pv.recv(proto_handler)
    pv.send(proto_handler, val_new + ' - nope')
    print(val_new)
Пример #20
0
import protocol as pv
import sys

if __name__ == "__main__":
    server_handler = pv.server_socket("localhost", int(sys.argv[1]))

    # listening for connections
    pv.recv(server_handler)

    val = 'do the lab'
    print(val)

    pv.send(server_handler, val)
    val = pv.recv(server_handler)
    print(val)

    val += ' - no, you!'
    pv.send(server_handler, val)
    val_new = pv.recv(server_handler)
    print(val_new)
Пример #21
0
    #         if folder_found:
    #             site_string += "\n================================================================================\n"
    #         site_string += "List of archives:\n" + "\n".join(archive_list)
    #     if site_string == "":
    #         site_string = "Sites not found!"
    #     protocol.send(connection, site_string)
    # elif command == "load":
    #     load = ""
    #     for i in range (1, 100000):
    #         load += str(i) + ' '
    #         if i % 1000 == 0:
    #             load += '\n'
    #     protocol.send(connection, load)
    # else:
    #     protocol.send(connection, "Invalid request")


def args_analysis(connection, args):
    args = args.split()
    handle_commands(connection=connection, command=args[0], string=args[1:])


sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((config.host, config.port))
sock.listen(True)
while True:
    conn, addr = sock.accept()
    print('Connected by ', addr)
    data = protocol.recv(conn)
    args_analysis(connection=conn, args=data)
Пример #22
0
        while string == '':
            print("Введите строку:")
            string = input()

        command = ''
        while command == '' or command not in ['', '1', '2']:
            print(
                "Выберите команду: 1 - реверс строки; 2 - перестановка четн. и нечетн. символов"
            )
            command = input()

        print("Вы выбрали", command)
        return

    elif options == '2':
        print("ПАКЕТНЫЙ режим работы.")


status = True
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((config.host, config.port))
protocol.send(sock, input())
data = protocol.recv(sock)
# while True:
print(data)

sock.close()

if status == False:
    sock.close()
Пример #23
0
 def recv(self):
     return protocol.recv(self.sock)