Python 在线程中处理 Socketserver 请求

标签 python multithreading sockets

在下一个示例中,我在线程中处理了 Socket 服务器。在句柄函数中,我们创建线程并传递请求和client_地址。 当我们在线程的运行方法中处理请求时,只能接收数据,但是当我尝试发送某些内容时,会引发异常([Errno 9] 错误的文件描述符) 怎么了?

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()

最佳答案

我认为您正在寻找 ThreadingMixIn :

from SocketServer import TCPServer, ThreadingMixIn

class MyServerThread(ThreadingMixIn, TCPServer): pass

关于Python 在线程中处理 Socketserver 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8534651/

相关文章:

python - 如何复制word文档的内容?

.NET 内核之间线程的移动

c++ - boost线程notify_all()和sleep()

c# - 多客户端,C#中的异步套接字,最佳实践?

python - Celery 使用默认代理而不是 reddis。 Flask + Celery + 工厂模式

python - 在 CPU 和 GPU 上的两个独立的 jupyter 笔记本中训练 Keras 模型

python - 如何用keras制作3D滤镜

java - 计时器计划与 scheduleAtFixedRate?

sockets - 接受套接字后会发生什么? [复制]

c# - 客户端关闭时 NetworkStream 在 Read() 上抛出异常