Merci de vos reponses c'est cool ! je connaissait déjà plus ou moins GitHub mais je n'y avais pas fait attention vraiment. J'en profite pour vous demander un avis sur mon programme de chat en python, il marche, j'ai même utilisé pickle pour faire une base de données stockant les mots de passe et les username des membres du serveur.
Je vous presente en premier mon 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 | import socket
import sys
import select
# main variables
_HOST = 'localhost' # host for the server
_PORT = 4500 # remote port
_BUFFER = 1024 # max buffering for data
_RUNNING = True # main variable to run the principal loop
_USERS = [] # list of all connected users
class Server: # socket chat server as an object
def __init__(self):
self.host = socket.gethostbyname(_HOST)
self.port = int(_PORT)
self.buffer = _BUFFER
self.run = _RUNNING
self.users = _USERS
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def broadcast_data(self, sock, data):
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 main(self):
try:
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
self.sock.listen(5)
self.users.append(self.sock)
except socket.error:
print('Unable to connect ot the remote host: {0}'.format(self.host))
print('Chat server started on port: ' + str(self.port) + '\n')
while 1:
read_sockets, write_sockets, in_error = select.select(self.users, [], [])
for sockp in read_sockets:
if sockp == self.sock:
# new connection
sockfd, addr = self.sock.accept()
self.users.append(sockfd)
print('Client ({0}) connected\n'.format(addr))
self.broadcast_data(sockfd, '[{0}] entered the chatroom\n'.format(addr))
# some incoming message from the client
else:
# data received from the client process it
try:
data = sockp.recv(self.buffer).decode()
if data:
print('\r' + '<' + str(sockp.getpeername()) + '> ' + data)
self.broadcast_data(sockp, data)
except socket.error:
self.broadcast_data(sockp, 'Client({0}) is offline\n'.format(addr))
print('Client({0}) is offline\n'.format(addr))
sockp.close()
try:
self.users.remove(sockp)
except socket.error:
print('\r')
continue
continue
self.sock.close()
if __name__ == '__main__':
server = Server()
server.main()
|
c'est moi qui l'ai réalisé en m'appuyant sur un exemple et votre aide.
Le code 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 | # required modules
import sys
import socket
import select
import hashlib
import pickle
if (len(sys.argv) < 5):
print('[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 = sys.argv[4].encode()
lock = True
database = {}
password = hashlib.sha1(PASSWORD).hexdigest()
with open('database.pickle', 'rb') as file:
while lock:
try:
loaded = pickle.load(file)
try:
if password == loaded[USERNAME]:
print('Authentification completed \n loading...')
lock = False
except KeyError:
database.update(loaded)
except EOFError:
break
sys.exit()
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 main(self):
try:
self.sock.connect((self.host, self.port))
except:
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:
sys.stdout.write(data)
self.prompt()
else:
data = sys.stdin.readline()
data = '[' + USERNAME + '] '+ data
self.sock.send(data.encode())
self.prompt()
client = Client()
client.main()
|
et enfin mon code qui sert au client à s'inscrire dans le 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 | import sys # manage outpouts
import hashlib # hash the password and encrypt it
import pickle # serialization of the database
database = {} # create a database as a dictionnary with passwords encrypted for keys
if len(sys.argv) < 3:
print('[Usage] python manager.py <username> <password>')
sys.exit()
username = sys.argv[1]
password = (sys.argv[2].encode())
password = hashlib.sha1(password).hexdigest()
database[username] = password
with open('database.pickle', 'ab') as file:
my_pickler = pickle.Pickler(file)
my_pickler.dump(database)
def database_loader():
with open('database.pickle', 'rb') as file:
while True:
try:
loaded = pickle.load(file)
except EOFError:
break
else:
database.update(loaded)
database_loader()
|
j'en suis assez content car c'est ma première création qui viens totalement de moi, pareil pour la partie de code dans le programme client qui vérifie si le mdp et le user sont corrects pour se connecter.
Qu'est ce que vous en pensez ? Que puis-je améliorer ? Merci.