For demonstration and educational purposes only — this server cannot support production projects
Note: Tests are not currently passing, need to be updated with recent refactor
A Small Socket Server Implementation in Python 3.10 with HTTP and WebSocket extensions.
Each different server can be started using the corresponding "run" script:
- Socket server:
run_socket_server.py
- WebSocket server:
run_websocket_server.py
- HTTP server:
run_http_server.py
Each server uses an event-observer system built into the base server itself to allow for
listening for certain message types and responding appropriately. To register a new listener, refer
to the register_listener
calls in each "run" script. Listeners can be assigned to respond based
on message "type", the determination of which is determined from the incoming data and can be handled
by adding overriding the get_message_type
class in the server class; currently this is only done
in the WebSocket server class (websocket/server.py
) since the other two classes, for demo purposes,
need only treat the incoming data as bytes/text. WebSockets need to understand specific message types
based on incoming headers to negotiate the handshake appropriately.
- Run the socket server with
python run_socket_server.py
- In a separate terminal window, use the
nc
(netcat) tool to communicate with the server- Using command like
echo "Hello I am the client!" | nc 127.0.0.1 8080
- Using command like
- You should see the message successfully being received and logged by the server, and a response given to the client
- Run the websocket server with
python run_websocket_server.py
- In a web browser, open up the Javascript console
- Using Javascript
- Create a new websocket connection
wsClient = new WebSocket("ws://127.0.0.1:9000");
- Initialize the appropriate listener to ensure you see the server response
wsClient.onmessage = console.log
- Send a message to the server
wsClient.send("Hello I am the client!")
- Create a new websocket connection
- You should see the message being received and logged by the server, and a response emitted in the JS console
- Run the HTTP server with
python run_http_server.py
- In the web browser, open a new tab at the server address of http://127.0.0.1:9000
- You should see the HTTP message received and logged by the server, and a valid HTML page rendered in the browser