简体   繁体   中英

Python Thread Not Starting

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

#!/usr/bin/python

import sys
import socket
import time
import threading

# 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')
        socket.send(userInput)
    socket.close

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
s.connect((host, port))
print "... connected to server!"
try:
   thread.start_new_thread( sendChat, (s, "sendChat" ) )
except:
   print "Error: unable to start thread"

time.sleep(100)

Here is what I get when I run it:

Ryans-MacBook-Pro:network ryan$ python chatclient.py
Hello, Python!
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

I have seen that the main thread can end before the new one so I tried add the sleep at the end but that didn't work.

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 thread module).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM