简单的Web服务器Python

时间:2018-11-12 20:15:43

标签: python-3.x web server

我无法使服务器正常工作。我正在尝试将txt文件推送到本地客户端。我不断收到对等点重置连接的错误。我该如何解决?这是我的代码。

import socket
from socket import *
from datetime import datetime
import sys

s = socket(AF_INET, SOCK_STREAM)

HOST = "127.0.0.2"  # Local client is going to be 127.0.0.1
PORT = 4300  # Open http://127.0.0.2:4300 in a browser
LOGFILE = "webserver.log"


def main():
    """Main loop"""
    with socket(AF_INET, SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen(1)
        print('Listening on port {}'.format(PORT))
        conn, addr = s.accept()
        print("Waiting for client response")
        with conn:
            while True:
                data = conn.recv(1024)
                dt = data.decode()
                print(dt)
                if not data:
                    print('Connection closed')
                    break
                if data:
                    filename = 'alice30.txt'
                    f = open(filename,'rb')
                    l = f.read(1024)
                    while (l):
                        conn.sendall(l)
                        print('Sent ',repr(l))
                        l = f.read(1024)
                    f.close()
                else:
                    print("Invalid")
                    conn.sendall("Invalid Request".encode())

                print("Waiting for client response")


if __name__ == "__main__":
    main()

我得到的回溯是:

Traceback (most recent call last):
  File "webserver.py", line 53, in <module>
    main()
  File "webserver.py", line 24, in main
    data = conn.recv(1024)
socket.error: [Errno 104] Connection reset by peer

我认为这与链接到重复项的问题不同。他们在回答中说这是服务器的问题。我的代码是服务器...我认为它必须处理来回发送的字节。

0 个答案:

没有答案