我想要用python编写线程服务器套接字。我从网上找到了这个密码。我工作很好,但我不知道发生了什么。 任何人都可以简单地解释一下,我想把数据从main发送到MiTcpHandler类。我怎么能做到呢?在
import SocketServer
import threading
import time
class MiTcpHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = ""
while data != 'End':
data = self.request.recv(1024)
print data
time.sleep(0.1)
class ThreadServer(SocketServer.ThreadingMixIn,SocketServer.ForkingTCPServer):
pass
def Main():
host=''
port = 9998
server = ThreadServer((host,port),MiTcpHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
Main()
如注释中所述,您应该阅读^{} 模块文档。它包括如何使用它的例子。从中你可以了解代码是如何工作的。在
关于问题的第二部分,如何将数据从“main”发送到线程,您需要建立到服务器的TCP连接(同一主机上的端口9998)。您可以使用^{} 进行此操作:
这将从充当客户端的主功能将数据发送到服务器。注意,您需要在处理程序中做更多的工作来正确处理连接的终止和终止
"End"
字符串的检测。在相关问题 更多 >
编程相关推荐