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

2021-02-26 14:29:12 发布

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