Shammer's Philosophy

My private adversaria

Python Socket Server

Python HTTP Post client - Shammerismでクライアントを書いたので、今度はサーバー。と言っても、複雑なことは何もせず決まった応答を返すだけのもの。ほとんどサンプルのコピー。。。

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        body = "<html><title>Test</title><body>It works!</body></html>\r\n"
        response = '\r\n'.join([
            "HTTP/1.1 200 OK",
            "Server: MyWebServer/1.1",
            "Content-Type: text/html;charset=UTF-8",
            "Content-Length: " + str(len(body)),
            ""
        ]);
        response = response + '\r\n' + body
        print response
        self.request.send(response)

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()