В следующем экзамене я обработал Socket-сервер в потоке. В функции handle мы создаем Thread и передаем request и client_ address .
Когда мы обрабатываем запрос в run-методе Thread, можно только получать данные, но когда я пытаюсь что-то отправить, возникает исключение ([Errno 9] Bad file descriptor)
Что не так?
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()