Created
July 15, 2019 22:04
-
-
Save wiomoc/00bfdb866e3f5383bc8d302d24a4d43f to your computer and use it in GitHub Desktop.
WebSocket Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
var ws = new WebSocket("ws://localhost:8080/"); | |
ws.onmessage = function (event) { | |
console.log(event.data); | |
} | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socketserver | |
import hashlib | |
import base64 | |
class WebSocketHandler(socketserver.StreamRequestHandler): | |
def handle(self): | |
self.rfile.readline() | |
hash = None | |
while True: | |
line = self.rfile.readline().decode("utf-8") | |
if line == "\r\n": | |
break | |
key = line[0:line.index(":")] | |
value = line[line.index(":") + 1:len(line) - 2].strip() | |
if key == "Sec-WebSocket-Key": | |
hash = base64.encodebytes( | |
hashlib.sha1((value + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode("utf-8")).digest())[:-1] | |
self.wfile.write(b"HTTP/1.1 101 Switching Protocols\r\n") | |
self.wfile.write(b"Upgrade: websocket\r\n") | |
self.wfile.write(b"Connection: Upgrade\r\n") | |
self.wfile.write("Sec-WebSocket-Accept: {0}\r\n".format(hash.decode("UTF-8")).encode("UTF-8")) | |
self.wfile.write(b"\r\n") | |
# https://tools.ietf.org/html/rfc6455#page-38 | |
self.wfile.write(b"\x81\x05Hello") # TEXT | |
self.wfile.write(b"\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58") # TEXT masked | |
self.wfile.write(b"\x82\x05World") # Binary | |
self.wfile.write(b"\x89\x00") # PING | |
self.wfile.write(b"\x01\x03Hel") # /Fragment: TEXT | |
self.wfile.write(b"\x00\x03lo ") # |Fragment: CONT | |
self.wfile.write(b"\x80\x05World")# \Framment: FIN CONT | |
server = socketserver.TCPServer(("localhost", 8080), WebSocketHandler) | |
server.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment