簡體   English   中英

在 python 中為 socket.io 創建服務器-客戶端測試

[英]Creating server-client tests for socket.io in python

任何人都可以指點一個完整的新手到我可以學習 Python 框架來測試 socket.io 的地方。 我非常擅長編寫測試靜態 API 的腳本,但之前從未使用過 WebSocket。

謝謝你的幫助!

在此處https://github.com/abourget/gevent-socketio/tree/master/examples 的gevent-socketIO 示例代碼中有大量使用多個流行框架的示例

如果你想使用 Python 與 socket.io 服務器通信,你可以使用socketIO-client

from socketIO_client import SocketIO

def on_bbb_response(*args):
    print 'on_bbb_response', args

with SocketIO('localhost', 8000) as socketIO:
    socketIO.emit('bbb', {'xxx': 'yyy'}, on_bbb_response)
    socketIO.wait_for_callbacks(seconds=1)

這是我嘗試過的。

服務器.py

import json
from aiohttp import web
import socketio

sio = socketio.AsyncServer()

# Creates a new Aiohttp Web Application
app = web.Application()
sio.attach(app)

@sio.on('message')
async def print_message(sid, data):
    print("worked :")
    if data['type'] == "enter":
        print("----- "+data['username'] + " joined the room -----")
    elif data['type'] == "exit":
        print("----- "+data['username'] + " left the room -----")
    else:
        print(data['username']+" > "+data['message'])

if __name__ == '__main__':
    web.run_app(app)

客戶端.py

import time
import socketio

sio = socketio.Client()

sio.connect('http://localhost:8080')

username = input("Enter username : ") or "Unknown"

sio.emit("message", {'username':username,'message':'','type':'enter'})

while True:
    print("Enter message : ")
    msg = input()
    sio.emit("message", {'username':username,'message':msg,'type':'chat'})
    print("to quit press y")
    key = input()

    if key == 'y' or key == 'Y':
        sio.emit("message", {'username': username, 'message': "",'type':'exit'})
        time.sleep(1)
        sio.disconnect()
        break

sio.emit("message", {'username': username, 'message': msg})

print("you disconnected")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM