Python线程无法启动

时间:2016-05-01 01:57:03

标签: python multithreading sockets

从几个不同的来源混淆代码我正在尝试创建一个python聊天客户端。我可以连接到服务器,但我想使用两个线程,所以我可以同时发送和接收消息。我是python的新手,无法让我的线程工作。我的python版本是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)

以下是我运行时的结果:

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

我已经看到主线程可以在新线程结束之前结束,所以我尝试在最后添加睡眠但是没有用。

1 个答案:

答案 0 :(得分:2)

好吧,使用完全符合的代码,你的全部try/except隐藏着明显的原因。如果我删除try/except,我会:

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

很明显,是吗?您没有导入thread模块,因此当然调用thread.start_new_thread()无法正常工作(您导入的是threading - 而应该使用低级thread模块)。