-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
54 lines (43 loc) · 1.34 KB
/
client.py
File metadata and controls
54 lines (43 loc) · 1.34 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
# Import required modules
import socket
import threading
HOST = '127.0.0.1'
PORT = 1234
def listen_for_messages_from_server(client):
while True:
message = client.recv(2048).decode('utf-8')
if message != '':
username = message.split("->")[0]
content = message.split("->")[1]
print(f"{username} -> {content}")
else:
print('Message received from clinet is empty.')
def send_message_to_server(client):
while True:
message = input("Message: ")
if message != '':
client.sendall(message.encode())
else:
print("Empty message")
exit(0)
def communicate_to_server(client):
username = input('Enter username: ')
if username != '':
client.sendall(username.encode())
else:
print('Username cannot be empty.')
exit(0)
threading.Thread(target=listen_for_messages_from_server, args=(client,)).start()
send_message_to_server(client)
# Main function
def main():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
try:
client.connect((HOST, PORT))
print("Successfully connected to server.")
except:
print(f"Unable to connect to server {HOST} {PORT}.")
communicate_to_server(client)
if __name__ == "__main__":
main()