在下一個檢查中,我在線程中處理了Socket服務器。在句柄函數中我們創建Thread並通過請求和client_ 地址。 當我們在線程的run-method中處理請求時,它只能接收數據,但是當我嘗試發送一個異常時,會引發異常([Errno 9]錯誤的文件描述符) 有什麼問題?Python處理線程中的Socketserver請求
import SocketServer
import threading
class MyServerThread(threading.Thread):
def __init__(self, channel, details):
self.channel = channel
self.details = details
threading.Thread.__init__(self)
def run(self):
print 'Received connection:', self.details[0]
self.channel.send('(Response)')
print 'Received:', self.channel.recv(1024)
self.channel.close()
print 'Closed connection:', self.details[0]
class MyThreadedSocketServerHandler(SocketServer.BaseRequestHandler):
def handle(self):
thread1 = MyServerThread(self.request, self.client_address)
thread1.start()
if __name__ == '__main__':
server = SocketServer.TCPServer(('localhost', 8888), MyThreadedSocketServerHandler)
server.serve_forever()
#---Client to test---
import socket
message = "(Request)"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect(('localhost', 8888))
sock.send(message)
data = sock.recv(1024)
print 'Sent: %s' % message
print 'Received: %s' % data
finally:
sock.close()
#Working example without "join"
import socket
import threading
class ClientThread(threading.Thread):
def __init__(self, channel, details):
self.channel = channel
self.details = details
threading.Thread.__init__(self)
def run(self):
print 'Received connection:', self.details[0]
self.channel.send('message')
print self.channel.recv(1024)
self.channel.close()
print 'Closed connection:', self.details[0]
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('', 8888))
server.listen(5)
while True:
channel, details = server.accept()
ClientThread(channel, details).start()
也許客戶端關閉的時候連接你試圖發送數據? – werewindle 2011-12-16 13:36:33