'Messages wont go through a simple chat using threads with Python
I've been trying to create a simple chat, my idea was to have 2 functions running in a loop on different threads, one is for sending messages and one is for receiving messages, I am prompted to enter messages which means that at least my sending messages thread works, and I also get connection success message but for some reason the messages are not reaching the other end.
this is my code:
server.py:
from socket import *
import threading
server = socket(AF_INET, SOCK_STREAM)
server.bind(("", 4444))
server.listen(5)
def acceptmessages():
while True:
data = client.recv(2048).decode()
print(data)
def sendmessages():
while True:
msg = input("Enter message > ").encode()
client.sendall(msg)
client, addr = server.accept()
print("New connection from Address: {0}".format(addr))
threading.Thread(target=sendmessages(), args=()).start()
threading.Thread(target=acceptmessages(),args=()).start()
client.py:
from socket import *
import threading
client = socket(AF_INET, SOCK_STREAM)
client.connect(("10.0.0.7", 4444))
def acceptmessages():
while True:
data = client.recv(2048).decode()
print(data)
def sendmessages():
while True:
msg = input("Enter message > ").encode()
client.sendall(msg)
threading.Thread(target=sendmessages(), args=()).start()
threading.Thread(target=acceptmessages(),args=()).start()
Solution 1:[1]
The problem was I called the function in the target field instead of passing the function, so instead of
threading.Thread(target=sendmessages(), args=()).start()
threading.Thread(target=acceptmessages(),args=()).start()
it needs to be
threading.Thread(target=sendmessages).start()
threading.Thread(target=acceptmessages).start()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Skity |
