用python编写服务器套接字线程

2024-09-30 10:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要用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()

Tags: importselfhostdataservertimemainport
1条回答
网友
1楼 · 发布于 2024-09-30 10:34:11

如注释中所述,您应该阅读^{}模块文档。它包括如何使用它的例子。从中你可以了解代码是如何工作的。在

关于问题的第二部分,如何将数据从“main”发送到线程,您需要建立到服务器的TCP连接(同一主机上的端口9998)。您可以使用^{}进行此操作:

def Main():
    host=''
    port = 9998
    server = ThreadServer((host,port),MiTcpHandler)
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.start()

    # connect to the server and send some data
    import socket
    s = socket.create_connection(('localhost', 9998))
    s.send('hi there\n')
    s.send('End\n')

这将从充当客户端的主功能将数据发送到服务器。注意,您需要在处理程序中做更多的工作来正确处理连接的终止和终止"End"字符串的检测。在

相关问题 更多 >

    热门问题