防止Python网络服务器关闭连接

时间:2019-06-11 15:00:51

标签: python sockets webserver

我有一个要执行以下操作的服务器:

(1)通过3次握手建立TCP连接

(2)通过发送文件来处理所有“ POST”方法请求

(3)保持连接打开状态,以处理更多的“ POST”请求,而无需进行新的握手

现在,连接已建立,接受第一个POST,然后在下一个POST中,服务器发送RST。

我尝试删除client.close(),但是没有运气。

import socket
import signal
import sys
import time
import threading

class WebServer(object):

    def __init__(self, port=8080):
        self.host = '0.0.0.0'
        self.port = port
        self.content_dir = 'web' # Directory where webpage files are stored

    def start(self):
                self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        try:
            print("Starting server on {host}:{port}".format(host=self.host, port=self.port))
            self.socket.bind((self.host, self.port))
            print("Server started on port {port}.".format(port=self.port))

        except Exception as e:
            print("Error: Could not bind to port {port}".format(port=self.port))
            self.shutdown()
            sys.exit(1)

        self._listen() # Start listening for connections

    def shutdown(self):
        """
        Shuts down the server
        """
        try:
            print("Shutting down server")
            s.socket.shutdown(socket.SHUT_RDWR)

        except Exception as e:
            pass # Pass if socket is already closed

    def _generate_headers(self, response_code, length):
        header = ''
        if response_code == 200:
            header += 'HTTP/1.1 200 OK\n'
        elif response_code == 404:
            header += 'HTTP/1.1 404 Not Found\n'

        time_now = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
        header += 'Date: {now}\n'.format(now=time_now)
        header += 'Content-Type: application/octect-stream\n'
        header += 'Cache-Control: no-cache\n'
        header += 'Connection: Keep-Alive\n'
        header += 'Keep-Alive: timeout=60\n'
        header += 'Content-Length: {}\n\n'.format(length)

        return header

    def _listen(self):
        """
        Listens on self.port for any incoming connections
        """
        self.socket.listen(5)
        while True:
            (client, address) = self.socket.accept()
            #client.settimeout(60)
            print("Recieved connection from {addr}".format(addr=address))
            threading.Thread(target=self._handle_client, args=(client, address)).start()

    def _handle_client(self, client, address):
        """
        Main loop for handling connecting clients and serving files from content_dir
        Parameters:
            - client: socket client from accept()
            - address: socket address from accept()
        """
        PACKET_SIZE = 1024
        while True:
            print("CLIENT",client)
            data = client.recv(PACKET_SIZE)

            if not data: break

            request_method = data.split(' ')[0]
            print("Method: {m}".format(m=request_method))
            print("Request Body: {b}".format(b=data))

            if request_method == "POST":
                file_requested = data.split(' ')[1]

                print("Serving file [{}]".format(file_requested))

                file_content = open(file_requested, 'rb').read()

                response_header = self._generate_headers(200, len(file_content))

                response = response_header + file_content

                client.send(response)
                client.close()
                break
            else:
                print("Unknown HTTP request method: {method}".format(method=request_method))


### MAIN ###
def shutdownServer(sig, unused):
    """
    Shutsdown server from a SIGINT recieved signal
    """
    server.shutdown()
    sys.exit(1)

signal.signal(signal.SIGINT, shutdownServer)
server = WebServer(443)
server.start()
print("Press Ctrl+C to shut down server.")

0 个答案:

没有答案