-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()方法的第二個線程似乎完全沒有這樣做。 –