-
Notifications
You must be signed in to change notification settings - Fork 0
/
echo-server.py
executable file
·37 lines (32 loc) · 1.06 KB
/
echo-server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python3
import socket
import websocket
import sys
def serve():
if len(sys.argv) < 3:
print('Usage: ./echo-server.py host port\n'\
'Example: ./echo-server.py 127.0.0.1 8080\n')
exit()
host = sys.argv[1]
port = int(sys.argv[2])
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen()
conn, addr = sock.accept()
handshake_request = conn.recv(2048)
print('-'*20)
print('Received handshake request:\n')
print(handshake_request.decode())
handshake_response = websocket.generate_server_handshake(handshake_request)
conn.sendall(handshake_response)
while(1):
opcode, payload, fin = websocket.decode_frame_from_sock(conn)
if (opcode == 1):
payload = payload.decode('utf-8')
response_frame = websocket.encode_frame(
websocket.OPCODES.index('text'), payload, False, False)
conn.send(response_frame)
else:
break
if __name__ == '__main__':
serve()