-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfull_duplex_chat_client.py
More file actions
51 lines (43 loc) · 1.48 KB
/
full_duplex_chat_client.py
File metadata and controls
51 lines (43 loc) · 1.48 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
#!/usr/bin/env python3
"""
TCP Full-Duplex Chat Client.
"""
from socket import *
from time import ctime
from threading import Event
from chatthreads import ReceiverThread, SenderThread
class ChatClient:
def __init__(self, host, port):
self.ADDR = (host, port)
self.threads = []
self._stop = Event()
def __call__(self):
# Make a TCP cliet socket
with socket(AF_INET, SOCK_STREAM) as client_socket:
# Connect to a remote (server) address
try:
client_socket.connect(self.ADDR)
except ConnectionRefusedError:
print('!!! Can\'t connect to the Chat Server...')
return
else:
print('*** Connection whit the Chat Server is established...\n***',
ctime())
# Spawn threads for a receiving and sending messages
for thrd in [ReceiverThread, SenderThread]:
self.threads.append(thrd(client_socket, self._stop))
# Trigger the spawned threads
for thrd in self.threads:
thrd.start()
# Wait for all threads to finish
try:
for thrd in self.threads:
thrd.join()
except KeyboardInterrupt:
# Exit from the Chat
print('\nGood bye all!')
if __name__ == '__main__':
HOST = "localhost"
PORT = 21567
chat_client = ChatClient(HOST, PORT)
chat_client()