-1
我是python新手,我正在尝试编写一个简单的聊天应用程序,其中包含一个运行线程的服务器,该线程可以接受并向连接的客户端发送消息,以及一个运行两个线程的客户端,分别向服务器发送消息和接受来自服务器的消息。下面的代码Python套接字聊天应用程序中的线程不会启动
服务器:
import socket
import sys
import thread
def receiveAndDeliverMessage(conn):
while True:
data = conn.recv(1040)
if not data: break
print(data)
conn.send(data)
conn.close
HOST = '' # Localhost
PORT = 8888 # Arbitrary non-privileged port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a TCP/IP socket
print 'Socket created'
#Bind socket to local host and port
try:
sock.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
sock.listen(10)
print 'Socket now listening'
# Create threads for receiving a connection from client and receiving data from client
while True:
connection, address = sock.accept() #Accept method returns a tupule containing a new connection and the address of the connected client
print 'Connected with ' + address[0] + ':' + str(address[1])
try:
thread.start_new_thread(receiveAndDeliverMessage, (connection))
except:
print ("Error: unable to start thread")
sock.close()
客户:
#Socket client example in python
import socket #for sockets
import sys #for exit
import thread
def sendMessage():
count = 0
while (count < 3):
message = raw_input('Write message to send to server: ');
count = count + 1
print 'message '+str(count)+': '+(message)
try :
#Send the whole string
sock.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message sent successfully to server'
def receiveMessage():
reply = sock.recv(1024)
print reply#Print the message received from server
#create an INET, STREAMing socket
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
print 'Socket Created'
serverHost = 'localhost'
serverPort = 8888
try:
remote_ip = socket.gethostbyname(serverHost)
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
#Connect to remote server
sock.connect((remote_ip , serverPort))
print 'Socket Connected to ' + serverHost + ' on ip ' + remote_ip
try:
thread.start_new_thread(receiveMessage,())
except:
print ("Error: unable to start receive message thread")
try:
thread.start_new_thread(sendMessage,())
except:
print ("Error: unable to start send message thread")
sock.close()#Close socket to send eof to server
现在每一个客户端被打开的时候,而不是它运行在服务器上运行receiveAndDelivermessage函数的线程,异常被抛出。所以我得到“错误:无法启动线程”。我不明白为什么抛出异常。也许我还没有完全理解线程是如何工作的。任何帮助不胜感激。此外,每次打开客户端时,都会在建立与服务器的连接后立即终止。
您使用的是包罗万象的,除了所以你不要看不到你在代码中犯的小错误,(连接)不是一个元素的元组,它只是'connection',所以'thread.start_new_thread'由于参数类型不正确而引发类型错误。 –
@Tadhg McDonald-Jensen好吧,我明白了。 (连接,地址)纠正它,现在它似乎工作正常。我仍然得不到的是客户端应用程序在与服务器建立连接后立即结束。应该触发sendMessage()方法的第二个线程似乎完全没有这样做。 –