-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
62 lines (46 loc) · 1.38 KB
/
server.py
File metadata and controls
62 lines (46 loc) · 1.38 KB
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
import socket
import threading
HOST = "127.0.0.1"
PORT = 9090
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
clients = []
nicknames = []
def broadcast(message:str):
'''
Envia para todos os clientes as mensagens
'''
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
print(f'{nicknames[clients.index(client)]} digitou {message}')
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
nicknames.remove(nickname)
break
def receive():
'''
Recebe as conexoes
'''
while True:
client, address = server.accept()
print(f"Conectado com {str(address)}\n")
client.send("NICK".encode("utf-8"))
nickname = client.recv(1024)
nicknames.append(nickname)
clients.append(client)
print(f'Nickname: {nickname}\n')
broadcast(f'{nickname} conectou ao servidor!\n'.encode('utf-8'))
client.send("Conectado ao Servidor\n".encode("utf-8"))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
print("Server iniciado...\n")
receive()