Postgresql python psycopg2

a marqué ce sujet comme résolu.

En fait je n'ai pas eu autant de temps que je voulais.

Pour résumer l'idée: actuellement sur ton serveur quand un client se connecte il ne peut faire qu'une chose, envoyer un seul type de message. L'idée ce serait que tu implémentes plusieurs commandes. Par exemple avec un préfixe, un peu comme IRC. Si le client envoie un "/create (user) (pass)" ça crée le client, s'il envoie un "/identify (user) (pass)" ça essaye de l'identifier, et s'il envoie "/message [le message]" ça envoie en message à tous les gens connectés et identifiés.

À mon avis c'est en partant sur ce genre de logique que tu arriveras au résultat voulu en minimisant le nombre d'efforts.

+0 -0

bonjour je viens d'avancer par rapport à ce que tu m'as dis, qu'est ce que tu en pense: voici le serveur: (j'ai utilisé des petits codes pour differencier les demandes)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import socket
import sys
import threading
import select
import sqlite3

# main variables
_HOST = '192.168.1.22'
_PORT = 4567
_BUFFER = 1024
_RUNNING = True
_USERS = []

# colors for different kinds of data
BLUE = '\033[94m'
GREEN = '\033[92m'
RED = '\033[1;31m'
PURPLE = '\033[1;34m'


print(PURPLE + " █████╗ ██████╗ ██████╗ ███████╗███╗   ██╗ █████╗ ██╗     ██╗███╗   ██╗███████╗    \n"
               " ██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗  ██║██╔══██╗██║     ██║████╗  ██║╚══███╔╝   \n"
               " ███████║██║  ██║██████╔╝█████╗  ██╔██╗ ██║███████║██║     ██║██╔██╗ ██║  ███╔╝    \n"
               " ██╔══██║██║  ██║██╔══██╗██╔══╝  ██║╚██╗██║██╔══██║██║     ██║██║╚██╗██║ ███╔╝     \n"
               " ██║  ██║██████╔╝██║  ██║███████╗██║ ╚████║██║  ██║███████╗██║██║ ╚████║███████╗   \n"
               " ╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═══╝╚═╝  ╚═╝╚══════╝╚═╝╚═╝  ╚═══╝╚══════╝   \n"
               " hammer05 - backtrack05 / v1.0 beta / contact me hammer1.adrenalinz@yahoo.com      \n")


class Server(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.host = socket.gethostbyname(_HOST)
        self.port = int(_PORT)
        self.buffer = _BUFFER
        self.run = _RUNNING
        self.users = _USERS
        self.username = {}
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def broadcast_data(self, sock, data):
        """ encode and send data to all connected users except the sender """
        for sockt in self.users:
            if sockt != self.sock and sockt != sock:
                try:
                    sockt.send(data.encode())
                except:
                    sockt.close()
                    self.users.remove(sockt)

    def broadcast_one(self, receiver, data):
        """ encode and send data to a receiver (used for new_account()) """
        for sockb in self.users:
            if sockb == receiver:
                try:
                    sockb.send(data.encode())
                except:
                    sockb.close()
                    self.users.remove(sockb)

    def new_account(self, requester, username, password):
        """ Create a new account and inject username and password in the database """
        conn = sqlite3.connect('database.db')
        cursor = conn.cursor()
        cursor.execute('IF NOT EXIST CREATE TABLE users (username TEXT NOT NULL UNIQUE, password TEXT NOT NULL UNIQUE)')

        try: # inject user datas into the database and create the account
            cursor.execute('INSERT INTO users VALUES(?, ?)', (username, password))
            conn.commit()
            self.broadcast_data(requester, 'your account has been created, restart the client to login with it')
            print(GREEN + '[' + requester + '] created a new account (' + username, password + ')\n')
            cursor.close()
            conn.close()
        except sqlite3.IntegrityError: # every username must be unique in the table
            self.broadcast_one(requester, RED + '/err your account could not be created : username already exists...')
            print(RED + 'User[' + requester + '] tried to create a new account: username already token... ERROR SENT\n')
            cursor.close()
            conn.close()

    def connector(self, requester, username, password):
        """ Verify in the database if username and password exists and allow or not the access to server """
        conn = sqlite3.connect('database.db')
        cursor = conn.cursor()
        account = (username, password)

        try:  # select username and password information
            cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', account)
            lock = cursor.fetchall()
            if username in lock and password in lock:
                self.broadcast_one(requester, GREEN + '/at access authorized...')
                print(GREEN + 'User[' + username + '] entered the chat-room')
                self.broadcast_data(requester, 'User[' + username + '] entered the chat-room')
                self.sock.append(requester)
            else:
                self.broadcast_one(requester, GREEN + '/an access denied...')
                print(RED + 'User[' + username + '] failed log in ERROR SENT\n')

        except:
            pass

    def main(self):
        """ In this function all others will be assembled as a puzzle to build the server """
        try:  # binding the server and listening incoming connections
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.sock.bind((self.host, self.port))
            self.sock.listen(10) # 10 connections MAX
            self.users.append(self.sock)
        except socket.error:
            print(RED + 'Unable to connect ot the remote host: {0}'.format(self.host))
            sys.exit()

        print(GREEN + 'Chat server started on port: ' + str(self.port) + '\r')

        while 1:
            read_sockets, write_sockets, in_error = select.select(self.users, [], [])

            for sockp in read_sockets:
                if sockp == self.sock:

                    sockfd, addr = self.sock.accept()
                    self.users.append(sockfd)

                else:
                    try:
                        data = sockp.recv(self.buffer).decode()
                        if data:
                            spliter = data.split()  # for data harvesting and differentiation

                            if '/i' == spliter[0]:  # register code new account will be created
                                user = spliter[1]  # data harvesting
                                passwd = spliter[2]  # data harvesting
                                self.new_account(sockp, user, passwd)

                            if '/a' == spliter[0]:  # connection code call the connect function
                                user = spliter[1]  # data harvesting
                                passwd = spliter[2]  # data harvesting
                                self.connector(sockp, user, passwd)

                            if '/q' == spliter[0]:  # exit code -> logged out of the server
                                user = spliter[1]  # data harvesting
                                print(RED + 'user[' + user + '] is off-line\n')
                                self.broadcast_data(sockp, RED + 'user[' + user + '] is off-line\n')

                            print('\r' + str(sockp.getpeername()) + data)
                            self.broadcast_data(sockp, '\r' + '(' + str(sockp.getpeername()) + ')' + ' ' + data)

                        else:
                            if sockp in self.users:
                                self.users.remove(sockp)

                            self.broadcast_data(sockp, 'Client({0}) is offline\r'.format(addr))
                            print('Client({0}) is offline\r'.format(addr))

                    except:

                        self.broadcast_data(sockp, 'Client({0}) is offline\r'.format(addr))
                        print('Client({0}) is offline\r'.format(addr))
                        continue
        self.sock.close()


if __name__ == '__main__':
    server = Server()
    server.main()

et le client:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import sqlite3
import sys
import socket
import select
import hashlib
import getpass

if len(sys.argv) < 3:
    print('[usage] python client.py <hostname> <port> <username> <password>')
    sys.exit()

# colors for different kinds of data
BLUE = '\033[94m'
GREEN = '\033[92m'
RED = '\033[1;31m'
PURPLE = '\033[1;34m'

HOST = str(sys.argv[1])
PORT = int(sys.argv[2])
USERNAME = str(sys.argv[3])
PASSWORD = hashlib.md5(str(sys.argv[4]).encode()).hexdigest()

print(PURPLE + " █████╗ ██████╗ ██████╗ ███████╗███╗   ██╗ █████╗ ██╗     ██╗███╗   ██╗███████╗    \n"
               " ██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗  ██║██╔══██╗██║     ██║████╗  ██║╚══███╔╝   \n"
               " ███████║██║  ██║██████╔╝█████╗  ██╔██╗ ██║███████║██║     ██║██╔██╗ ██║  ███╔╝    \n"
               " ██╔══██║██║  ██║██╔══██╗██╔══╝  ██║╚██╗██║██╔══██║██║     ██║██║╚██╗██║ ███╔╝     \n"
               " ██║  ██║██████╔╝██║  ██║███████╗██║ ╚████║██║  ██║███████╗██║██║ ╚████║███████╗   \n"
               " ╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═══╝╚═╝  ╚═╝╚══════╝╚═╝╚═╝  ╚═══╝╚══════╝   \n"
               " hammer05 - backtrack05 / v1.0 beta / contact me hammer1.adrenalinz@yahoo.com      \n")
class Client:
    def __init__(self):
        self.host = HOST
        self.port = PORT
        self.run = True
        self.buff = 1024
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(2)

    def prompt(self):
        sys.stdout.write('<you> ')
        sys.stdout.flush()

    def connect(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn = (self.host, self.port)
        try:
            sock.connect(conn)
            while self.run:
                response = sock.recv(1024)
                sock.send('/a' + USERNAME + ' ' + PASSWORD)
                if response:
                    code = response.decode().split()
                    if code[0] == '/at':
                        sock.close()
                        print('[client commands]\n'
                              '/li: show all connected users\n'
                              '/q: to leave the chat-room\n')
                        self.main()
        except socket.error:
            print(RED + 'An error occurred... EXIT[1]\n')
            sys.exit()

    def main(self):
        try:
            self.sock.connect((self.host, self.port))
        except socket.error:
            print('Unable to connect to the remote host: {0}'.format(self.host))
            sys.exit()

        print('connected to the remote host. Start sending messages')
        self.prompt()

        while 1:
            rlist = [sys.stdin, self.sock]

            read_list, write_list, error_list = select.select(rlist, [], [])

            for sock in read_list:

                if sock == self.sock:
                    data = self.sock.recv(self.buff).decode()
                    if not data:
                        print('\nDisconnected from chat server')
                        sys.exit()
                    if data:
                        print('\r' + data)
                        self.prompt()
                else:
                    data = sys.stdin.readline()
                    self.sock.send(data.encode())
                    self.prompt()

je dois encore implémenter l'inscription mais qu'est ce que tu en penses?

J'ai pas eu trop le temps de regarder dans les détails. D'un point de vue purement macro y'a de l'idée (utiliser des threads par exemple), mais quelques petits trucs qui révèlent une conception pas très sûre d'elle.

Par exemple tu as une méthode connector qui est un nom (au lieu d'un verbe). Tu utilises aussi le même thread pour tout le serveur (ce qui revient à ne pas utiliser de threads du tout).

À ta place j'aurais écrit une classe Connector qui tourne dans son propre thread pour éviter de bloquer le serveur lorsqu'un client se connecte (je suppose toujours qu'une requête SQL prend du temps…) et le reste du serveur dans son thread à lui (comme précédemment).

Lorsqu'un client est connecté tu passes la socket d'un objet à l'autre (tu transfères la responsabilité de la socket du connector au serveur).

En dehors de ça, c'est plutôt un bon départ, que tu vas raffiner avec le temps.

+0 -0

bonjour j'ai reconstruit mon programme comme tu m'as conseillé: serveur:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import socket
import sys
import threading
import select
import sqlite3

# main variables
_HOST = '192.168.1.22'
_PORT = 4567
_BUFFER = 1024
_RUNNING = True
_USERS = []

# colors for different kinds of data
BLUE = '\033[94m'
GREEN = '\033[92m'
RED = '\033[1;31m'
PURPLE = '\033[1;34m'


print(PURPLE + " █████╗ ██████╗ ██████╗ ███████╗███╗   ██╗ █████╗ ██╗     ██╗███╗   ██╗███████╗    \n"
               " ██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗  ██║██╔══██╗██║     ██║████╗  ██║╚══███╔╝   \n"
               " ███████║██║  ██║██████╔╝█████╗  ██╔██╗ ██║███████║██║     ██║██╔██╗ ██║  ███╔╝    \n"
               " ██╔══██║██║  ██║██╔══██╗██╔══╝  ██║╚██╗██║██╔══██║██║     ██║██║╚██╗██║ ███╔╝     \n"
               " ██║  ██║██████╔╝██║  ██║███████╗██║ ╚████║██║  ██║███████╗██║██║ ╚████║███████╗   \n"
               " ╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═══╝╚═╝  ╚═╝╚══════╝╚═╝╚═╝  ╚═══╝╚══════╝   \n"
               " hammer05 - backtrack05 / v1.0 beta / contact me hammer1.adrenalinz@yahoo.com      \n")


class Query(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.sql = sqlite3.connect('database.db')
        self.query = self.sql.cursor()

    def broadcast_one(self, receiver, lister, data):
        """ encode and send data to a receiver (used for new_account()) """
        for sockb in lister:
            if sockb == receiver:
                try:
                    sockb.send(data.encode())
                except:
                    sockb.close()
                    lister.remove(sockb)

    def inscription(self, requester, username, password, lister):
        """ Used to create a new account in server's database """
        self.query.execute('IF NOT EXISTS CREATE TABLE users_data'
                           ' (username TEXT NOT NULL UNIQUE,'
                           ' password TEXT NOT NULL UNIQUE)')
        try:
            self.query.execute('INSERT INTO users_data VALUES(?, ?)', (username, password))
            self.sql.commit()
            print(GREEN + '[' + requester + '] created a new account (' + username, password + ')\n')
            self.broadcast_one(requester, lister, '/op')
        except sqlite3.IntegrityError:
            print(RED + 'User[' + requester + '] tried to create a new account: username already token... ERROR SENT\n')
            self.broadcast_one(requester, lister, '/er')

    def connect(self, requester, username, password, lister):
        """ Used to check if users data is already in dataabse and allowing access to server """
        account = (username, password)
        self.query.execute('SELECT * FROM users WHERE username = ? AND password = ?', account)
        lock = self.query.fetchall()

        if username in lock and password in lock:
            print(GREEN + 'User[' + username + '] entered the chat-room')
            self.broadcast_one(requester, lister, '/at access authorized...')

        else:
            print(RED + 'User[' + requester + '] failed log in ERROR SENT\n')
            self.broadcast_one(requester, lister, RED + '/ad access denied...')

Sqlrequests = Query()  # instance the class to use it in Server()


class Server(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.host = socket.gethostbyname(_HOST)
        self.port = int(_PORT)
        self.buffer = _BUFFER
        self.run = _RUNNING
        self.users = _USERS
        self.username = {}
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def broadcast_data(self, sock, data):
        """ encode and send data to all connected users except the sender """
        for sockt in self.users:
            if sockt != self.sock and sockt != sock:
                try:
                    sockt.send(data.encode())
                except:
                    sockt.close()
                    self.users.remove(sockt)

    def broadcast_one(self, receiver, data):
        """ encode and send data to a receiver (used for new_account()) """
        for sockb in self.users:
            if sockb == receiver:
                try:
                    sockb.send(data.encode())
                except:
                    sockb.close()
                    self.users.remove(sockb)

    def main(self):
        """ In this function all others will be assembled as a puzzle to build the server """
        try:  # binding the server and listening incoming connections
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.sock.bind((self.host, self.port))
            self.sock.listen(10) # 10 connections MAX
            self.users.append(self.sock)
        except socket.error:
            print(RED + 'Unable to connect ot the remote host: {0}'.format(self.host))
            sys.exit()

        print(GREEN + 'Chat server started on port: ' + str(self.port) + '\r')

        while 1:
            read_sockets, write_sockets, in_error = select.select(self.users, [], [])

            for sockp in read_sockets:
                if sockp == self.sock:

                    sockfd, addr = self.sock.accept()
                    self.users.append(sockfd)

                else:
                    try:
                        data = sockp.recv(self.buffer).decode()
                        if data:
                            spliter = data.split()  # for data harvesting and differentiation

                            if '/i' == spliter[0]:  # register code new account will be created
                                user = spliter[1]  # data harvesting
                                passwd = spliter[2]  # data harvesting
                                Sqlrequests.inscription(sockp, user, passwd, self.users)

                            if '/a' == spliter[0]:  # connection code call the connect function
                                user = spliter[1]  # data harvesting
                                passwd = spliter[2]  # data harvesting
                                Sqlrequests.connect(sockp, user, passwd, self.users)

                            if '/q' == spliter[0]:  # exit code -> logged out of the server
                                user = spliter[1]  # data harvesting
                                print(RED + 'user[' + user + '] is off-line\n')
                                self.broadcast_data(sockp, RED + 'user[' + user + '] is off-line\n')
                                self.users.remove(sockp)

                            print('\r' + str(sockp.getpeername()) + data)
                            self.broadcast_data(sockp, '\r' + '(' + str(sockp.getpeername()) + ')' + ' ' + data)

                        else:
                            if sockp in self.users:
                                self.users.remove(sockp)

                            self.broadcast_data(sockp, 'Client({0}) is offline\r'.format(addr))
                            print('Client({0}) is offline\r'.format(addr))

                    except:

                        self.broadcast_data(sockp, 'Client({0}) is offline\r'.format(addr))
                        print('Client({0}) is offline\r'.format(addr))
                        continue
        self.sock.close()


if __name__ == '__main__':
    server = Server()
    server.main()

j'ai fait une classe à part pour les options sql de connexion et d'inscription…

voici le client qui sert à se connecter grace a sys.argv:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import sys
import socket
import select
import hashlib

# colors for different kinds of data
BLUE = '\033[94m'
GREEN = '\033[92m'
RED = '\033[1;31m'
PURPLE = '\033[1;34m'

if len(sys.argv) < 3:
    print(RED + '[usage] python client.py <hostname> <port> <username> <password>')
    sys.exit()

HOST = str(sys.argv[1])
PORT = int(sys.argv[2])
USERNAME = str(sys.argv[3])
PASSWORD = hashlib.md5(str(sys.argv[4]).encode()).hexdigest()

print(PURPLE + " █████╗ ██████╗ ██████╗ ███████╗███╗   ██╗ █████╗ ██╗     ██╗███╗   ██╗███████╗    \n"
               " ██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗  ██║██╔══██╗██║     ██║████╗  ██║╚══███╔╝   \n"
               " ███████║██║  ██║██████╔╝█████╗  ██╔██╗ ██║███████║██║     ██║██╔██╗ ██║  ███╔╝    \n"
               " ██╔══██║██║  ██║██╔══██╗██╔══╝  ██║╚██╗██║██╔══██║██║     ██║██║╚██╗██║ ███╔╝     \n"
               " ██║  ██║██████╔╝██║  ██║███████╗██║ ╚████║██║  ██║███████╗██║██║ ╚████║███████╗   \n"
               " ╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═══╝╚═╝  ╚═╝╚══════╝╚═╝╚═╝  ╚═══╝╚══════╝   \n"
               " hammer05 - backtrack05 / v1.0 beta / contact me hammer1.adrenalinz@yahoo.com      \n")


class Client:
    def __init__(self):
        self.host = HOST
        self.port = PORT
        self.run = True
        self.buff = 1024
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(2)

    def prompt(self):
        sys.stdout.write(RED + '<you> ')
        sys.stdout.flush()

    def connect(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn = (self.host, self.port)
        try:
            sock.connect(conn)
            while self.run:
                response = sock.recv(1024)
                sock.send(('/a' + USERNAME + ' ' + PASSWORD).encode())
                if response:
                    code = response.decode().split()
                    if code[0] == '/at':
                        sock.close()
                        print('[client commands]\n'
                              '/li: show all connected users\n'
                              '/q: to leave the chat-room\n')
                        self.main()
        except socket.error:
            print(RED + 'An error occurred... EXIT[1]\n')
            sys.exit()

    def main(self):
        try:
            self.sock.connect((self.host, self.port))
        except socket.error:
            print('Unable to connect to the remote host: {0}'.format(self.host))
            sys.exit()

        print('connected to the remote host. Start sending messages')
        self.prompt()

        while 1:
            rlist = [sys.stdin, self.sock]

            read_list, write_list, error_list = select.select(rlist, [], [])

            for sock in read_list:

                if sock == self.sock:
                    data = self.sock.recv(self.buff).decode()
                    if not data:
                        print('\nDisconnected from chat server')
                        sys.exit()
                    if data:
                        print('\r' + data)
                        self.prompt()
                else:
                    data = sys.stdin.readline()
                    if data == '/q':
                        data = data + ' ' + USERNAME
                    self.sock.send(data.encode())
                    self.prompt()

if __name__ == '__main__':
    C = Client()
    C.connect()

et voici un fichier fait exprès pour s'inscrire dans la base du serveur:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import sqlite3
import sys
import socket
import hashlib

# colors for different kinds of data
BLUE = '\033[94m'
GREEN = '\033[92m'
RED = '\033[1;31m'
PURPLE = '\033[1;34m'

if len(sys.argv) < 3:
    print(RED + '[Usage] python inscriptor.py <username> <password>')
    sys.exit()

USERNAME = sys.argv[1]
PASSWORD = hashlib.md5(sys.argv[2].encode()).hexdigest()

print(PURPLE + " █████╗ ██████╗ ██████╗ ███████╗███╗   ██╗ █████╗ ██╗     ██╗███╗   ██╗███████╗    \n"
               " ██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗  ██║██╔══██╗██║     ██║████╗  ██║╚══███╔╝   \n"
               " ███████║██║  ██║██████╔╝█████╗  ██╔██╗ ██║███████║██║     ██║██╔██╗ ██║  ███╔╝    \n"
               " ██╔══██║██║  ██║██╔══██╗██╔══╝  ██║╚██╗██║██╔══██║██║     ██║██║╚██╗██║ ███╔╝     \n"
               " ██║  ██║██████╔╝██║  ██║███████╗██║ ╚████║██║  ██║███████╗██║██║ ╚████║███████╗   \n"
               " ╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═══╝╚═╝  ╚═╝╚══════╝╚═╝╚═╝  ╚═══╝╚══════╝   \n"
               " hammer05 - backtrack05 / v1.0 beta / contact me hammer1.adrenalinz@yahoo.com      \n")


class Temporally:
    def __init__(self):
        self.host = '192.168.1.22'
        self.port = 4567
        self.user = USERNAME
        self.password = PASSWORD
        self.run = True
        self.buffer = 1024
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def main(self):
        try:
            self.sock.connect((self.host, self.port))

        except socket.error:
            print(RED + 'An error occurred... EXIT[1]')
            sys.exit()

        print(GREEN + 'creation of your account...\n')

        while self.run:
            response = self.sock.recv(self.buffer)
            self.sock.send(('/i ' + USERNAME + ' ' + PASSWORD).encode())

            if response:
                code = response.decode().split()
                if code[0] == '/op':
                    print(GREEN + 'Account created! connect to it using client.py')
                    self.sock.close()
                    sys.exit()
                elif code[0] == '/er':
                    print(RED + 'Username already exists... use another one')
                    sys.exit()

if __name__ == '__main__':
    T = Temporally()
    T.main()

petit problème quand je run le serveur puis le fichier d'inscription rien ne s'affiche (pas d'erreur, pas de message de succès d'inscription comme dû…) cela est-il dû au manque de thread ??? Merci et bonne soirée

Connectez-vous pour pouvoir poster un message.
Connexion

Pas encore membre ?

Créez un compte en une minute pour profiter pleinement de toutes les fonctionnalités de Zeste de Savoir. Ici, tout est gratuit et sans publicité.
Créer un compte