An example of using Websocket developed by Python

Posted by starmikky on Fri, 17 Jan 2020 15:14:10 +0100

I learned how to implement web development in java. Today I want to try to implement it in python, so I found the code on the Internet

2.1. Effect 1 (a client connects to the service and sends a message)

2.2. Effect 2 (another client connects to the service and sends a message)

2.3. Effect 3 (the service receives all messages from the client and returns messages)

2.4. Effect 4 (dropping one client does not affect other socket connections)

2.5. Effect 5 (list all connected client objects and client objects currently sending messages)

3. Core code
3.1,Python

#! -*- coding: utf-8 -*-
"""
Author: ZhenYuSha
Create Time: 2019-1-14
Info: Websocket Use example of
"""
import asyncio
import websockets

websocket_users = set()


# Check the client's permission. The user name and password can exit the cycle only after passing
async def check_user_permit(websocket):
    print("new websocket_users:", websocket)
    websocket_users.add(websocket)
    print("websocket_users list:", websocket_users)
    while True:
        recv_str = await websocket.recv()
        cred_dict = recv_str.split(":")
        if cred_dict[0] == "admin" and cred_dict[1] == "123456":
            response_str = "Congratulation, you have connect with server..."
            await websocket.send(response_str)
            print("Password is ok...")
            return True
        else:
            response_str = "Sorry, please input the username or password..."
            print("Password is wrong...")
            await websocket.send(response_str)


# Receive the client message and process it. Here, simply return the message sent by the client
async def recv_user_msg(websocket):
    while True:
        recv_text = await websocket.recv()
        print("recv_text:", websocket.pong, recv_text)
        response_text = f"Server return: {recv_text}"
        print("response_text:", response_text)
        await websocket.send(response_text)


# Server side main logic
async def run(websocket, path):
    while True:
        try:
            await check_user_permit(websocket)
            await recv_user_msg(websocket)
        except websockets.ConnectionClosed:
            print("ConnectionClosed...", path)    # Link disconnect
            print("websocket_users old:", websocket_users)
            websocket_users.remove(websocket)
            print("websocket_users new:", websocket_users)
            break
        except websockets.InvalidState:
            print("InvalidState...")    # invalid state
            break
        except Exception as e:
            print("Exception:", e)


if __name__ == '__main__':
    print("127.0.0.1:8181 websocket...")
    asyncio.get_event_loop().run_until_complete(websockets.serve(run, "127.0.0.1", 8181))
    asyncio.get_event_loop().run_forever()


3.2,Html(JS)

    <script>
        var socket;
        if ("WebSocket" in window) {
            var ws = new WebSocket("ws://127.0.0.1:8181/test");
            socket = ws;
            ws.onopen = function() {
                console.log('Successful connection');
                alert("Successful connection, Please enter your account and password");
            };
            ws.onmessage = function(evt) {
                var received_msg = evt.data;
                document.getElementById("showMes").value+=received_msg+"\n";
            };
            ws.onclose = function() {
                alert("Disconnected");
            };
        } else {
            alert("Browser does not support WebSocket");
        }
        function sendMeg(){
            var message=document.getElementById("name").value+":"+document.getElementById("mes").value;
            document.getElementById("showMes").value+=message+"\n\n";
            socket.send(message);
        }
    </script>

4. Github source sharing
https://github.com/ShaShiDiZhuanLan/Demo_Socket_Python

247 original articles published, praised by 115, visited 70000+
Private letter follow

Topics: socket Python github Web Development