36 lines
1003 B
Python
36 lines
1003 B
Python
import socket
|
|
import threading
|
|
|
|
|
|
# this function is for receiving messages from the server (broadcasted from the other clients)
|
|
def receive_messages(s):
|
|
while True:
|
|
try:
|
|
message = s.recv(1024).decode()
|
|
if not message:
|
|
print("\nDisconnected from server.")
|
|
break
|
|
# overwrites the current line to keep the UI clean
|
|
print(f"\rIncoming: {message}")
|
|
print("You: ", end="", flush=True)
|
|
except:
|
|
print("\nConnection lost.")
|
|
break
|
|
|
|
|
|
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
client_socket.connect(("localhost", 12345))
|
|
print("Connected to Group Chat.")
|
|
|
|
# thread to listen for messages while we are typing
|
|
receive_thread = threading.Thread(target=receive_messages, args=(client_socket,))
|
|
receive_thread.start()
|
|
|
|
while True:
|
|
msg = input("You: ")
|
|
if msg.lower() == "quit":
|
|
break
|
|
client_socket.send(msg.encode())
|
|
|
|
client_socket.close()
|