iT邦幫忙

第 12 屆 iT 邦幫忙鐵人賽

DAY 10
0
自我挑戰組

30天搞懂Python系列 第 10

[第10天]30天搞懂Python-網路程式

前言

利用websocket實作網路應用程式。

程式實作

安裝 websockets

pip install websockets

https://ithelp.ithome.com.tw/upload/images/20200925/201071435SkLNKh2Wf.jpg

建立一個 socket server

#!/usr/bin/env python
import asyncio
import websockets

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

    greeting = f"Hi {name}!"

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

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

asyncio.get_event_loop().run_until_complete(start_server)
print("Server is running port:8888")
asyncio.get_event_loop().run_forever()
chmod 755 WebsocketSrv.py

https://ithelp.ithome.com.tw/upload/images/20200925/20107143fWatkWNSkd.jpg

建立一個 socket client

#!/usr/bin/env python
import asyncio
import websockets
async def hello():
    uri = "ws://localhost:8888"
    async with websockets.connect(uri) as websocket:
        name = input("Your name?")

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

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

asyncio.get_event_loop().run_until_complete(hello())
chmod 755 WebsocketClient.py

https://ithelp.ithome.com.tw/upload/images/20200925/20107143IFvNojwChf.jpg

程式執行結果

執行Server

https://ithelp.ithome.com.tw/upload/images/20200925/201071432WxJdUVSMA.jpg

執行Client

https://ithelp.ithome.com.tw/upload/images/20200925/20107143ZWIRIiuTVq.jpg

Server執行結果

https://ithelp.ithome.com.tw/upload/images/20200925/20107143AfQdEk9HDF.jpg


上一篇
[第09天]30天搞懂Python-網頁爬蟲-GoodInfo股市資訊
下一篇
[第11天]30天搞懂Python-機器學習(scikit-learn)
系列文
30天搞懂Python30

尚未有邦友留言

立即登入留言