forked from MMKLab/tcp-chat-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
threaded_tcp_chat_client.py
55 lines (47 loc) · 1.57 KB
/
threaded_tcp_chat_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
from socket import *
from time import sleep
from threading import *
class ListenThread(Thread):
def __init__(self, sock):
self.sock = sock
# Calling a constructor of 'Thread' class
super().__init__()
# self.start() essentially runs the run() method below
self.start()
def run(self):
print('Now listening!')
# Just keeps receiving messages as they come and prints them
while True:
print( self.sock.recv(4096).decode() )
# Static vars
srv_address = 'localhost'
srv_port = 2222
# Input
username = input('Enter your username: ')
# Establish connection to the server
while True:
try:
# Make a socket
sock = socket(AF_INET, SOCK_STREAM)
# Connect to the server
sock.connect( (srv_address, srv_port) )
print('Connected to {} on port {}'.format(srv_address, srv_port))
# Send our username to the server
sock.send(username.encode())
# Initialize the listener so we can receive messages
# And send them at the same time
listener = ListenThread(sock)
# We have connected so we can get out of the infinite loop
break
except:
# Pretty self-explanatory
print('Unable to connect to the server')
print('Retrying in 5 seconds...')
# Does nothing for 5 seconds, then goes back to the try block
sleep(5)
# Main chat loop
while True:
# Get user input
message = input()
# Send it to the server
sock.send(message.encode())