Mashing code from a few different sources I am trying to make a python chat client. I can connect to the server but I want to use two threads so I can send and recieve messages at the same time. I am new to python and cannot get my threads to work. My python version is 2.7.5
# Define a function for the thread
def sendChat( socket, name):
userInput = ""
while userInput != "exit":
userInput = raw_input("What do you want to say")
userInput = (userInput+'\r\n')
print "Hello, Python!"
userName = raw_input("What would you like your user name to be:")
print (userName + " welcome to chatclient, connecting to server now...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
host = socket.gethostname() # Get local machine name
port = 4444
print "... connected to server!"
thread.start_new_thread( sendChat, (s, "sendChat" ) )
print "Error: unable to start thread"
Ryans-MacBook-Pro:network ryan$ python chatclient.py
What would you like your user name to be:ryan
ryan welcome to chatclient, connecting to server now...
... connected to server!
Error: unable to start thread
Well, with the code exactly as given, your catch-all
try/except is hiding the obvious cause. If I remove the
try/except, I get:
Traceback (most recent call last): File "ga.py", line 26, in <module> thread.start_new_thread( sendChat, (s, "sendChat" ) ) NameError: name 'thread' is not defined
Obvious, yes? You didn't import the
thread module, so of course calling
thread.start_new_thread() can't possibly work (you imported
threading instead - which you should be using instead of the low-level