I recently picked up python and I am trying to learn more about networking. I came across a problem, where I am trying to both listen and send data at the same time using multi threading. Here is the code:
import socket
from threading import Thread
name = ""
s = socket.socket()
def Main():
print("What is your name?")
name = input("Name: ")
Connect()
def Connect():
host = '127.0.0.1'
port = 5000
s.connect((host, port))
Thread(target=Send()).start()
print("oh")
Listen()
def Listen():
while True:
data, addr = s.recvfrom(1024)
data = data.decode('utf-8')
if not data:
break
print(data)
def Send():
message = input(name + ": ")
while message != 'q':
s.send(message.encode("utf-8"))
message = input(name + ": ")
s.close()
Main()
The problem is that when the Thread
is created, the program is stuck in the while loop of the Send()
function, and it never calls the Listen()
function. I added a print()
function to debug whether anything happens after the thread is created.
This is the output that I got:
What is your name?
Name: FlowR
: test
:
You are calling the Send()
function instead of passing it as parameters, that's why it blocks.
Drop the ()
after target=Send()
:
Thread(target=Send).start()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments