-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
65 lines (57 loc) · 2.03 KB
/
client.py
File metadata and controls
65 lines (57 loc) · 2.03 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
61
62
63
64
65
import re
import socket
import threading
#constantly refresh chat for new messages from server
def refresh_chat(server):
while True:
try:
msg = server.recv(1024)
print(msg.decode())
except:
pass
#Exchange username and welcome message from server
def welcome_handshake(server, username):
server.send(username.encode())
welcome = server.recv(1024).decode()
print(welcome)
#I got this regex template from https://www.geeksforgeeks.org/python-program-to-validate-an-ip-address/
#I used this regex, because it is a standard template for checking if a string is a valid ip address
def checkIP(ip):
regex = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)'''
return re.search(regex, ip)
def main():
print("- - - Chat Client - - -")
address = (input("Enter Server IP Address: "), 1717)
username = input("Enter username: ")
#Attempt to connect to server
#Checks that IP address is valid to avoid crashing client
sock = socket.socket()
connection = False
while not connection:
try:
if checkIP(address[0]):
sock.connect(address)
connection = True
else:
raise ValueError("Not a valid IP address!")
except:
print("Unable to connect to host!")
address = (input("Enter Server IP Address: "), 1717)
#On a successful connection, exchange welcome handshake and start new thead for chat refreshes
welcome_handshake(sock, username)
threading.Thread(target=refresh_chat,args=(sock,)).start()
while True:
msg = input()
if msg == '!exit':
break
elif len(msg) == 0:
continue
sock.send(msg.encode())
#if the msg equals "!exit" send the message and close the socket
sock.send(msg.encode())
sock.close()
if __name__ == '__main__':
main()