本文实例讲述了Python提示[Errno 32]Broken pipe导致线程crash错误解决方法。分享给大家供大家参考。具体方法如下:
1. 错误现象
ThreadingHTTPServer 实现的 http 服务,如果客户端在服务器返回前,主动断开连接,则服务器端会报 [Errno 32] Broken pipe 错,并导致处理线程 crash.
下面先看个例子,python 版本: 2.7
示例代码
代码如下:#!/usr/bin/env python
#!coding=utf-8
import os
import time
import socket
import threading
from BaseHTTPServer import HTTPServer ,BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
"""
处理get请求
"""
query=self.path
print "query: %s thread=%s" % (query, str(threading.current_thread()))
#ret_str="<html>" + self.path + "<br>" + str(self.server) + "<br>" + str(self.responses) + "</html>"
ret_str="<html>" + self.path + "<br>" + str(self.server) + "</html>"
time.sleep(5)
try:
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(ret_str)
except socket.error, e:
print "socket.error : Connection broke. Aborting" + str(e)
self.wfile._sock.close() # close socket
self.wfile._sock=None
return False
print "success prod query :%s" % (query)
return True
#多线程处理
class ThreadingHTTPServer(ThreadingMixIn,HTTPServer):
pass
新闻热点
疑难解答