成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

websocket簡單使用

fxp / 1085人閱讀

摘要:簡單實現(xiàn)參考此文章只限于版本大于前期準備端這里會在開始連接時就調(diào)用這里會挺住等待發(fā)送消息先執(zhí)行這里在這里停住等待二加密實現(xiàn)這里應(yīng)該是要填寫加密的文件此處沒有深入研究三服務(wù)器和瀏覽器的實現(xiàn)此處先執(zhí)行代碼然后再打開瀏覽器就可以看到過程同步例子

簡單實現(xiàn)

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

前期準備

pip install websocket

server端

import asyncio
import websockets

async def hello(websocket, path):
    print(path)                    #這里會在client開始連接時就調(diào)用
    name = await websocket.recv()       #這里會挺住,等待client發(fā)送消息
    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)   #先執(zhí)行這里
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())  
二:加密實現(xiàn)

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"))  #這里應(yīng)該是要填寫加密的文件,此處沒有深入研究

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())
三:服務(wù)器和瀏覽器的實現(xiàn)

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:此處先執(zhí)行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提供一個查看當前狀態(tài)的接口
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())

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/42894.html

相關(guān)文章

  • WebSocket簡單介紹及應(yīng)用

    摘要:一旦建立了連接,此后的通信就不再使用了,改為使用獨立的數(shù)據(jù)幀這個幀有辦法看到,見后文。在里看到的,就是的數(shù)據(jù)幀了可以看到很像聊天記錄,其中用淺綠色標注的是由客戶端發(fā)送給服務(wù)器的部分。 定時刷新的不足與改進 web開發(fā)中可能遇到這樣的場景:網(wǎng)頁里的某一塊區(qū)域里寫了一些內(nèi)容,但這些內(nèi)容不是固定的,即使看網(wǎng)頁的人沒有做任何操作,它們也會隨時間不斷變化。股票行情、活動或游戲的榜單都是比較常見的...

    OBKoro1 評論0 收藏0
  • 簡單又好用的聊天室技術(shù)——WebSocket

    摘要:國際慣例,先上維基百科的解釋。維基百科上面是維基百科對的解釋,別問我如何解釋上面這段話,因為我也沒看懂,那么下面我用人話解釋一下吧僅僅是我的理解是一個協(xié)議,可以簡單看成是協(xié)議的一個補充協(xié)議,借助協(xié)議的基礎(chǔ)完成服務(wù)器主動與客戶端實時傳輸數(shù)據(jù)。 現(xiàn)在,很多網(wǎng)站為了實現(xiàn)推送技術(shù),所用的技術(shù)都是輪詢。輪詢是在特定的的時間間隔(如每1秒),由瀏覽器對服務(wù)器發(fā)出HTTP request,然后由服務(wù)...

    Prasanta 評論0 收藏0
  • WebSocket就是這么簡單

    摘要:是一個持久化的協(xié)議,相對于這種非持久的協(xié)議來說。最大的特點就是實現(xiàn)全雙工通信客戶端能夠?qū)崟r推送消息給服務(wù)端,服務(wù)端也能夠?qū)崟r推送消息給客戶端。參考鏈接知乎問題原理原理知乎問題編碼什么用如果文章有錯的地方歡迎指正,大家互相交流。 前言 今天在慕課網(wǎng)上看到了Java的新教程(Netty入門之WebSocket初體驗):https://www.imooc.com/learn/941 WebS...

    hikui 評論0 收藏0
  • Node.js+WebSocket創(chuàng)建簡單聊天室

    摘要:好的,這樣以來我們的前期準備工作就已經(jīng)完成了,下面我們來搭建聊天室對應(yīng)的客戶端和服務(wù)器端。 websocket簡介 websocket其實HTML中新增加的內(nèi)容,其本質(zhì)還是一種網(wǎng)絡(luò)通信協(xié)議,以下是websocket的一些特點: (1)因為連接在端口80(ws)或者443(wss)上創(chuàng)建,與HTTP使用的端口相同,幾乎所有的防火墻都不會阻塞WebSocket鏈接 (2)因...

    cppprimer 評論0 收藏0
  • Node.js+WebSocket創(chuàng)建簡單聊天室

    摘要:好的,這樣以來我們的前期準備工作就已經(jīng)完成了,下面我們來搭建聊天室對應(yīng)的客戶端和服務(wù)器端。 websocket簡介 websocket其實HTML中新增加的內(nèi)容,其本質(zhì)還是一種網(wǎng)絡(luò)通信協(xié)議,以下是websocket的一些特點: (1)因為連接在端口80(ws)或者443(wss)上創(chuàng)建,與HTTP使用的端口相同,幾乎所有的防火墻都不會阻塞WebSocket鏈接 (2)因...

    Seay 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<