套接字聊天应用程序中的Python线程无法启动

时间:2016-08-13 23:40:26

标签: python multithreading sockets networking chat

我是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函数的线程。所以我得到了“错误:无法启动线程”。我不明白为什么抛出异常。也许我还没有完全理解线程是如何工作的。任何帮助非常感谢。此外,每次打开客户端时,都会在建立与服务器的连接后立即终止。

1 个答案:

答案 0 :(得分:1)

您吞下原始例外并打印出自定义消息,因此很难确定导致问题的原因。因此,我将提供有关调试问题的一些提示。

    try:
        thread.start_new_thread(receiveAndDeliverMessage, (connection))
    except:
        print ("Error: unable to start thread")

您正在一个except块中捕获所有类型的异常,这非常糟糕。即使您这样做,也要尝试查找消息 -

except Exception as ex:
    print(ex)

或者您也可以获得完整的回溯,而不仅仅是打印异常:

import traceback
tb = traceback.format_ex(ex)