'Writing my own WebSocket using the python socket server module

I wanted to know how WebSocket servers are written so I tried making my own. I used this as my reference and wrote a simple ThreadedTCPServer from the socket server module this is my code for it

import base64
import hashlib
import re
import socketserver


def make_headers(headers: dict):
    result = ""
    result += "HTTP/1.1 101 Switching Protocols\r\n"
    for header, value in headers.items():
        result += f"{header}: {value}\r\n"
    return result


def get_key(handshake_string):
    key = re.findall(r"Sec-WebSocket-Key: .*", handshake_string)[0]
    key = key.split(":")[1].strip()
    return key


class Handler(socketserver.BaseRequestHandler):
    MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

    def setup(self) -> None:
        handshake_text = self.request.recv(1024).decode('utf-8')
        print(handshake_text)
        key = get_key(handshake_text)
        key = key + self.MAGIC
        print(key)
        key = hashlib.sha1(key.encode()).digest()
        key = base64.b64encode(key).decode()
        print(key)

        headers = {"Upgrade": "websocket", "Connection": "Upgrade",
                   "Sec-WebSocket-Accept": key}

        headers = make_headers(headers)
        self.request.send(headers.encode())

    def handle(self) -> None:
        self.request.send(b"Connection Finally works ^_^")
        print("conn sent?")

    def finish(self) -> None:
        print("Connection Over :(")


if __name__ == '__main__':
    server = socketserver.ThreadingTCPServer(("127.0.0.1", 2449), Handler)
    server.serve_forever()

As mentioned in the referenced site, I have implemented the handshake in the setup method of my handler class however when I open my simple HTML document for testing the server I don't get my desired result in the browser console (blank) this is my html code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Socket test</title>
</head>
<body>
<h1>Sample text1</h1>
<script>
    var ws = new WebSocket("ws://127.0.0.1:2449/")
    ws.onopen = function() {
        console.log("Connection Established!")
    }

    ws.onmessage = function(msg)
    {
        console.log("message received!")
        console.log(msg)
    }

    ws.onerror = function(err){
        console.log(err)
    }
</script>
</body>
</html>

The html page sends a socket request which triggers the server handler and upon the handshake the request closes. is there any reason as to why this happens?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source