【问题标题】:Creating server-client tests for socket.io in python在 python 中为 socket.io 创建服务器-客户端测试
【发布时间】:2012-09-25 18:10:51
【问题描述】:

任何人都可以将一个完整的新手指向我可以学习 Python 框架以测试 socket.io 的地方。我非常擅长编写用于测试静态 API 的脚本,但之前从未使用过 WebSocket。

感谢您的帮助!

【问题讨论】:

标签: python websocket socket.io


【解决方案1】:

这里https://github.com/abourget/gevent-socketio/tree/master/examplesgevent-socketIO的示例代码中有大量使用多个流行框架的示例@

【讨论】:

    【解决方案2】:

    如果你想使用 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)
    

    【讨论】:

      【解决方案3】:

      这是我尝试过的。

      server.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)
      
      

      client.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")
      
      

      【讨论】:

        猜你喜欢
        • 2019-07-20
        • 1970-01-01
        • 2019-05-09
        • 2017-04-18
        • 1970-01-01
        • 1970-01-01
        • 2015-09-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多