'Receiving messages off the same socket in different threads - Python
I'm looking to build a chat room in python at the moment and am struggling with direct messages as I'm using client.recv(2048) function in both my thread listening for messages from the server and trying to use client.recv() in my main function to receive a list of active users on the server. It seems the program will work sometimes and others will shift to the clientreceive function.
Thread started
# Starts thread for client receive
receive_thread = threading.Thread(target=client_receive)
receive_thread.start()
receive block
def client_receive():
while True:
try:
message = client.recv(2048).decode()
print(message)
except:
client.close()
break
main method (DM)
if msg_type == "DM":
# Sends C DM message to server
dm_msg = "C DM"
client.send(dm_msg.encode())
# Receives list of online users from server in client_receive
users = client.recv(2048).decode()
print(users)
# Client inputs username and message to server
target = input("Select user: ")
chat = input("> ")
chat_msg = "D " + target + "|||||" + chat
I attempted using locks in my main method, which did not seem to work. I expected my method to stay with my socket when I used lock.acquire(), however it still broke to the clientreceive function
Thanks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
