资讯专栏INFORMATION COLUMN

websocket简单使用

fxp / 877人阅读

摘要:简单实现参考此文章只限于版本大于前期准备端这里会在开始连接时就调用这里会挺住等待发送消息先执行这里在这里停住等待二加密实现这里应该是要填写加密的文件此处没有深入研究三服务器和浏览器的实现此处先执行代码然后再打开浏览器就可以看到过程同步例子

简单实现

参考:https://websockets.readthedoc...
PS:此文章只限于python版本大于3.6

前期准备

pip install websocket

server端

import asyncio
import websockets

async def hello(websocket, path):
    print(path)                    #这里会在client开始连接时就调用
    name = await websocket.recv()       #这里会挺住,等待client发送消息
    print(f"< {name}")

    greeting = f"Hello {name}!"

    await websocket.send(greeting)
    print(f"> {greeting}")

start_server = websockets.serve(hello, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)   #先执行这里
asyncio.get_event_loop().run_forever()                      #在这里停住,等待

client

import asyncio
import websockets

async def hello():
    async with websockets.connect(
            "ws://localhost:8765") as websocket:
        name = input("What"s your name? ")

        await websocket.send(name)
        print(f"> {name}")

        greeting = await websocket.recv()
        print(f"< {greeting}")

asyncio.get_event_loop().run_until_complete(hello())  
二:加密实现

server

import asyncio
import pathlib
import ssl
import websockets

async def hello(websocket, path):
    name = await websocket.recv()
    print(f"< {name}")

    greeting = f"Hello {name}!"

    await websocket.send(greeting)
    print(f"> {greeting}")

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(
    pathlib.Path(__file__).with_name("localhost.pem"))  #这里应该是要填写加密的文件,此处没有深入研究

start_server = websockets.serve(
    hello, "localhost", 8765, ssl=ssl_context)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

client

import asyncio
import pathlib
import ssl
import websockets

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.load_verify_locations(
    pathlib.Path(__file__).with_name("localhost.pem"))

async def hello():
    async with websockets.connect(
            "wss://localhost:8765", ssl=ssl_context) as websocket:
        name = input("What"s your name? ")

        await websocket.send(name)
        print(f"> {name}")

        greeting = await websocket.recv()
        print(f"< {greeting}")

asyncio.get_event_loop().run_until_complete(hello())
三:服务器和浏览器的实现

server

import asyncio
import datetime
import random
import websockets

async def time(websocket, path):
    while True:
        now = datetime.datetime.utcnow().isoformat() + "Z"
        await websocket.send(now)
        await asyncio.sleep(random.random() * 3)

start_server = websockets.serve(time, "127.0.0.1", 5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

browser



    
        WebSocket demo
    
    
        
    
PS:此处先执行server代码,然后再打开浏览器就可以看到过程
同步例子

server

import asyncio
import json
import logging
import websockets

logging.basicConfig()

STATE = {"value": 0}

USERS = set()

def state_event():
    return json.dumps({"type": "state", **STATE})

def users_event():
    return json.dumps({"type": "users", "count": len(USERS)})

async def notify_state():
    if USERS:       # asyncio.wait doesn"t accept an empty list
        message = state_event()
        await asyncio.wait([user.send(message) for user in USERS])

async def notify_users():
    if USERS:       # asyncio.wait doesn"t accept an empty list
        message = users_event()
        await asyncio.wait([user.send(message) for user in USERS])

async def register(websocket):
    USERS.add(websocket)
    await notify_users()

async def unregister(websocket):
    USERS.remove(websocket)
    await notify_users()

async def counter(websocket, path):
    # register(websocket) sends user_event() to websocket
    await register(websocket)
    try:
        await websocket.send(state_event())
        async for message in websocket:
            data = json.loads(message)
            if data["action"] == "minus":
                STATE["value"] -= 1
                await notify_state()
            elif data["action"] == "plus":
                STATE["value"] += 1
                await notify_state()
            else:
                logging.error(
                    "unsupported event: {}", data)
    finally:
        await unregister(websocket)

asyncio.get_event_loop().run_until_complete(
    websockets.serve(counter, "localhost", 6789))
asyncio.get_event_loop().run_forever()

client



    
        WebSocket demo
        
    
    
        
-
?
+
? online
websocket提供一个查看当前状态的接口
python -m websockets wss://echo.websocket.org/

如果Python版本是3.5以下

server

import asyncio
import websockets

@asyncio.coroutine
def hello(websocket, path):
    name = yield from websocket.recv()
    print("< {}".format(name))

    greeting = "Hello {}!".format(name)

    yield from websocket.send(greeting)
    print("> {}".format(greeting))

start_server = websockets.serve(hello, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

client

import asyncio
import websockets

@asyncio.coroutine
def hello():
    websocket = yield from websockets.connect(
        "ws://localhost:8765/")

    try:
        name = input("What"s your name? ")

        yield from websocket.send(name)
        print("> {}".format(name))

        greeting = yield from websocket.recv()
        print("< {}".format(greeting))

    finally:
        yield from websocket.close()

asyncio.get_event_loop().run_until_complete(hello())

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/42894.html

相关文章

  • WebSocket简单介绍及应用

    摘要:一旦建立了连接,此后的通信就不再使用了,改为使用独立的数据帧这个帧有办法看到,见后文。在里看到的,就是的数据帧了可以看到很像聊天记录,其中用浅绿色标注的是由客户端发送给服务器的部分。 定时刷新的不足与改进 web开发中可能遇到这样的场景:网页里的某一块区域里写了一些内容,但这些内容不是固定的,即使看网页的人没有做任何操作,它们也会随时间不断变化。股票行情、活动或游戏的榜单都是比较常见的...

    OBKoro1 评论0 收藏0
  • 简单又好用的聊天室技术——WebSocket

    摘要:国际惯例,先上维基百科的解释。维基百科上面是维基百科对的解释,别问我如何解释上面这段话,因为我也没看懂,那么下面我用人话解释一下吧仅仅是我的理解是一个协议,可以简单看成是协议的一个补充协议,借助协议的基础完成服务器主动与客户端实时传输数据。 现在,很多网站为了实现推送技术,所用的技术都是轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP request,然后由服务...

    Prasanta 评论0 收藏0
  • WebSocket就是这么简单

    摘要:是一个持久化的协议,相对于这种非持久的协议来说。最大的特点就是实现全双工通信客户端能够实时推送消息给服务端,服务端也能够实时推送消息给客户端。参考链接知乎问题原理原理知乎问题编码什么用如果文章有错的地方欢迎指正,大家互相交流。 前言 今天在慕课网上看到了Java的新教程(Netty入门之WebSocket初体验):https://www.imooc.com/learn/941 WebS...

    hikui 评论0 收藏0
  • Node.js+WebSocket创建简单聊天室

    摘要:好的,这样以来我们的前期准备工作就已经完成了,下面我们来搭建聊天室对应的客户端和服务器端。 websocket简介 websocket其实HTML中新增加的内容,其本质还是一种网络通信协议,以下是websocket的一些特点: (1)因为连接在端口80(ws)或者443(wss)上创建,与HTTP使用的端口相同,几乎所有的防火墙都不会阻塞WebSocket链接 (2)因...

    cppprimer 评论0 收藏0
  • Node.js+WebSocket创建简单聊天室

    摘要:好的,这样以来我们的前期准备工作就已经完成了,下面我们来搭建聊天室对应的客户端和服务器端。 websocket简介 websocket其实HTML中新增加的内容,其本质还是一种网络通信协议,以下是websocket的一些特点: (1)因为连接在端口80(ws)或者443(wss)上创建,与HTTP使用的端口相同,几乎所有的防火墙都不会阻塞WebSocket链接 (2)因...

    Seay 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<