In the next examlpe I have Socket server handled in the thread. In the handle function we create Thread and pass request and client_address. When we handle the request in run-method of the Thread it's only possible to receive data, but when I try to send somthing an Exception is raised ([Errno 9] Bad file descriptor) What's wrong?
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()
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)