简体   繁体   English

在python中线程化服务器套接字

[英]threading the server socket in python

I want threading server socket in python. 我想在python中线程化服务器套接字。 and I found this code from internet. 我从互联网上找到了这段代码。 I works pretty good but I don't know what is happening. 我的工作还不错,但是我不知道发生了什么。 anyone can briefly explain it and I want to send data from main to MiTcpHandler class. 任何人都可以简要解释一下,我想将数据从main发送到MiTcpHandler类。 How can I do that? 我怎样才能做到这一点?

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

As mentioned in a comment you should have a read of the SocketServer module documentation. 如评论中所述,您应该阅读SocketServer模块文档。 It includes examples of how to use it. 它包括如何使用它的示例。 From that you can get an understanding of how the code works. 由此,您可以了解代码的工作原理。

For the second part of your question, how to send data from "main" to the thread, you need to establish a TCP connection to the server (port 9998 on the same host). 对于问题的第二部分,如何将数据从“主”发送到线程,您需要建立与服务器的TCP连接(同一主机上的端口9998)。 You can use socket.create_connection() for that: 您可以为此使用socket.create_connection()

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

This will send the data to the server from the main function which is acting as a client. 这将从充当客户端的主要功能将数据发送到服务器。 Note that you need to do some more work in the handler to properly handle termination of the connection and detection of the terminating "End" string. 请注意,您需要在处理程序中做更多工作,以正确处理连接的终止和终止"End"字符串的检测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM