monroews / CEE4530

MIT License
4 stars 11 forks source link

OSError: [WinError 10038]/ error from my project on python http server #125

Open Windys2 opened 5 years ago

Windys2 commented 5 years ago

hi to all, following codes bring some errors that confused me a lot, really appreciate some help. i'm new here and didn't figure out how to upload a markdown file yet. sorry about the messy display below

1st part is python code on http server as below

`import socket

import threading

class WebServer():

def __init__(self):
    server_socket = socket.socket()
    server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    server_socket.bind(("",8000))
    server_socket.listen(128)
    self.type = server_socket

def run(self):

    while True:
        new_server,client_id = self.type.accept()
        sub_thread = threading.Thread(target=WebServer.answer_client,args=(new_server,client_id))
        sub_thread.start()

@staticmethod
def answer_client(new_server, client_id):
    while True:
        receive_info = new_server.recv(1024).decode()
        if receive_info:
            print(receive_info, "from", client_id)
            request_path = receive_info.split(maxsplit=2)[1]
            response_line = "HTTP/1.1 200 OK\r\n"
            response_header = "Server: WS/1.1\r\n"
            try:
                with open("static" + request_path, "rb") as file:
                    response_body = file.read()
            except Exception:
                if request_path == "/":
                    response_line = "HTTP/1.1 200 OK\r\n"
                    request_path = "/index.html"
                else:
                    response_line = "HTTP/1.1 404 not found\r\n"
                    request_path = "/error.html"
            with open("static" + request_path, "rb") as file:
                response_body = file.read()
            send_info = (response_line + response_header + "\r\n").encode() + response_body
            new_server.send(send_info)
            new_server.close() # if I make this line into comment, this server didn't work properly, i'm so confused
        else:
            print(client_id, "break connection")
            break
    new_server.close()

def main(): web_server = WebServer() web_server.run()

if name == 'main': main()`

2nd part is html code for returning page to browser

<!DOCTYPE` html>

Welcome

Welcome to Our's Python Web Server!

If you see this page, the python web server is successfully installed and working. Further configuration is required.

Thank you for using.

` > **3rd part is json used for ajax within above html** > `{"name":"Tom","age":20}` >