Python线程在socket聊天应用程序中不会

2024-04-27 02:31:33 发布

您现在位置: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()

客户:

^{pr2}$

现在每次打开客户机时,都会抛出异常,而不是服务器上运行receiveAndDelivermessage函数的线程。所以我得到了“错误:无法启动线程”。我不明白为什么会抛出异常。也许我还没有完全掌握线程的工作原理。非常感谢任何帮助。而且,每次打开客户机时,在与服务器建立连接后,它会立即终止。在


Tags: andimport服务器消息客户端dataaddresssocket
1条回答
网友
1楼 · 发布于 2024-04-27 02:31:33

您吞下原始异常并打印出一条自定义消息,因此很难确定导致问题的原因。所以我将提供一些关于调试这个问题的提示。在

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

在一个except块中捕获所有类型的异常,这是非常糟糕的。即使你这么做了,也要试着找出其中的信息-

^{pr2}$

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

^{3}$

相关问题 更多 >