-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
59 lines (45 loc) · 1.54 KB
/
client.py
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
import socket
import threading
class Client:
def __init__(self, host, port):
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = host
self.port = port
self.nickname = None
def connect(self):
self.connection.connect((self.host, self.port))
def disconnect(self):
self.connection.close()
def register(self, nickname):
self.nickname = nickname
self.connection.send(nickname.encode('UTF8'))
def start_chat(self):
receive_thread = threading.Thread(target=self.receive)
receive_thread.start()
send_thread = threading.Thread(target=self.send)
send_thread.start()
def receive(self):
while True:
try:
message = self.connection.recv(1024).decode('UTF8')
print(message)
except Exception as erro:
print(f'Ocorreu um erro no recebimento das mensagens: {erro}')
self.disconnect()
break
def send(self):
while True:
try:
message = f"{self.nickname}: {input(f'{self.nickname}:')}"
self.connection.send(message.encode('UTF8'))
except Exception as erro:
print(f'Ocorreu um erro no envio das mensagens: {erro}')
self.disconnect()
break
def main():
client = Client('127.0.0.1', 7976)
client.connect()
client.register(input("Nickname:"))
client.start_chat()
if __name__ == "__main__":
main()