问题
例外的原因是什么?
client导致错误吗?
如果可能的话,请解释其他错误。
背景
我正在创建一个Python GUI套接字服务器。当客户端连接到我的服务器时,GUI窗口将打开(我仍在处理此问题)。但是,当客户端连接时,我收到错误:
Unhandled exception in thread started by <function clientthread at 0x10246c230>
由于实际脚本很长,我有provided a pastebin link.
这是线程代码。 s
是我的socket
对象的名称。
def clientthread(s):
#Sending message to connected client
#This only takes strings (words
s.send("Welcome to the server. Type something and hit enter\n")
#loop so that function does not terminate and the thread does not end
while True:
#Receiving from client
data = s.recv(1024)
if not data:
break
s.sendall(data)
print data
s.close()
回溯
感谢您提出的建议Morten。这是追溯。
Socket Created
Socket Bind Complete
Socket now listening
Connected
Traceback (most recent call last):
File "/Users/BigKids/Desktop/Coding/Python 2/Sockets/Function/Server GUI Alpha Function.py", line 80, in clientthread
s.send("Welcome to the server. Type something and hit enter\n")
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
就个人而言,我认为很多错误都是由于GUI造成的。
谢谢!
答案 0 :(得分:2)
首先,您可以捕获异常,打印并查看它是什么:)
这样做,例如通过try / except子句将其全部包围并打印出现的异常。
def clientthread(s):
try:
#Sending message to connected client
#This only takes strings (words
s.send("Welcome to the server. Type something and hit enter\n")
#loop so that function does not terminate and the thread does not end
while True:
#Receiving from client
data = s.recv(1024)
if not data:
break
s.sendall(data)
print data
s.close()
except Exception:
import traceback
print traceback.format_exc()
我猜这是客户端断开的原因。这将导致异常,您应该适当地处理它。如果客户端可以通过多种方式断开连接。告诉你,通过超时,在你尝试发送东西时丢弃连接等。 所有这些场景都是合理的例外情况,您应该对它们进行测试并处理它们。希望这会帮助你继续前进,如果没有,请评论:)