【问题标题】:Python thread in socket chat application won't start套接字聊天应用程序中的 Python 线程不会启动
【发布时间】:2016-08-13 23:40:25
【问题描述】:

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

【问题讨论】:

  • 您正在使用 catch all except 所以您看不到您在代码中犯的微不足道的错误,(connection) 不是一个元素的元组,它只是 connection 所以@ 987654325@ 由于参数类型不正确而引发类型错误。
  • @Tadhg McDonald-Jensen 好的,我明白了。用 (connection,address) 纠正了它,现在它似乎工作正常。我仍然不明白为什么客户端应用程序在与服务器建立连接后立即结束。应该触发 sendMessage() 方法的第二个线程似乎根本没有这样做。

标签: python multithreading sockets networking chat


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2018-01-29
    • 2017-01-14
    相关资源
    最近更新 更多