websocket 单点通信,广播通信

目录

应用场景:

一,单点通信

      1,server.py

        2,python 客户端 client.py

        3,html客户端client.html

        4,启动  :

二,广播消息

        1,server.py

        2,client.py

        3,html

      4,终端启动服务端 

        5,打开多个终端启动多个客户端

        6,打开html页面,点击登录WebSocket按钮

        7,输入框输入消息,点击发送消息

三,html 聊天室功能

        1,server.py 

      2,  client.html

        3,打开3个client.html 客户端,并发送数据

​编辑

四,单人聊天功能分析


        Websocket协议是对http的改进,可以实现client 与 server之间的双向通信; websocket连接一旦建立就始终保持,直到client或server 中断连接,弥补了http无法保持长连接的不足,方便了客户端应用与服务器之间实时通信。

参考:

HTML5 WebSocket | 菜鸟教程

由浅入深介绍 Python Websocket 编程-CSDN博客

应用场景:

        html单点通信

        消息群发

        聊天室功能

一,单点通信

      1,server.py

import asyncio
import websockets
from datetime import datetime

async def handler(websocket):
    data = await websocket.recv()
    reply = f"收到数据:{data}  time: {datetime.now()}"
    print(reply)
    await websocket.send(reply)
    print("Send reply")


async def main():
    async with websockets.serve(handler, "localhost", 9999):
        await asyncio.Future()  # run forever

if __name__ == "__main__":
    asyncio.run(main())


        2,python 客户端 client.py

import asyncio
import websockets
import time

async def ws_client(url):
    for i in range(1, 40):
        async with websockets.connect(url) as websocket:
            await websocket.send("Hello, I'm client 1")
            response = await websocket.recv()
        print(response)
        time.sleep(3)


if __name__ == "__main__":
    asyncio.run(ws_client('ws://127.0.0.1:9999'))

        3,html客户端client.html

<!DOCTYPE HTML>
<html>

<head>
    <meta charset="utf-8">
    <title>websocket demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js">		</script>
    <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script type="text/javascript">

            async function wsClient(url) {
                for (let i = 1; i <= 40; i++) {
                    const websocket = new WebSocket(url);

                    // Wait for the WebSocket connection to open
                    await new Promise((resolve, reject) => {
                        websocket.addEventListener('open', () => {
                            resolve();
                        });
                        websocket.addEventListener('error', reject);
                    });

                    // Send a message to the server
                    websocket.send("Hello, I'm client html");

                    // Wait for a response from the server
                    const response = await new Promise((resolve) => {
                        websocket.addEventListener('message', (event) => {
                            resolve(event.data);
                        });
                    });

                    // Print the response
                    console.log(response);

                    // Wait for 3 seconds before sending the next message
                    await new Promise(resolve => setTimeout(resolve, 1000));

                    // Close the WebSocket connection before the next iteration
                    websocket.close();
                }
            }                
 
        // C
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值