在Python中使用Socket-IO实现WebSocket

使用Socket-IO的Python WebSocket

WebSocket协议是实现实时应用程序的广泛支持的标准。它有助于在服务器和客户端之间的实时世界中转换为跨平台。Websockets与HTTP连接相比具有一个优势,它提供了全双工通信。通常,WebSockets与套接字混淆,WebSockets与套接字之间的区别如下:

WebSocketSocket.IO
通过TCP连接建立的协议。使用WebSocket的库。
通过TCP提供全双工通信。在服务器和客户端之间提供基于事件的通信。
不支持代理和负载平衡器。可以在代理和负载平衡器存在的情况下建立连接。
没有广播。支持广播。

在众多可用的库中,有python-socketio用于在python中实现WebSocket功能。

在虚拟环境中安装库

  • 创建虚拟环境
    -bash-4.2$python3 -m venv venv

  • 源(或激活)虚拟环境
    -bash-4.2$source venv/bin/activate

  • 使用pip安装所需的库

    (venv) -bash-4.2$ pip install python-socketio
    ...
    Successfully installed python-engineio-3.9.3 python-socketio-4.3.1
    
    (venv) -bash-4.2$ pip install aiohttp
    ...
    Successfully installed aiohttp-3.6.1 async-timeout-3.0.1 idna-ssl-1.1.0 
    multidict-4.5.2 typing-extensions-3.7.4 yarl-1.3.0

服务器代码示例(socket_io_server.py)

from aiohttp import web
import socketio
import os

# 创建一个新的aysnc套接字io服务器
socket_io = socketio.AsyncServer()

#创建一个新的Aiohttp Web应用程序
web_app = web.Application()

#将socket.io服务器绑定到Web应用程序实例
socket_io.attach(web_app)

#定义端点 
async def index(request):
    dirname = os.path.dirname(__file__)
    filename = os.path.join(dirname, '/templates/index.html')
    with open(filename) as file_obj:
        return web.Response(text = file_obj.read(), content_type='text/html')


@socket_io.on('message')
async def print_message(id, message):
    print("socket id is {}".format(id))
    print(message)
    #实现双向通讯
    await socket_io.emit('message', "you said {}".format(message))


#将aiohttp端点绑定到web_application
web_app.router.add_get('/',index)

#启动服务器
if __name__ == '__main__':
    web.run_app(web_app)

客户端代码示例(index.html)

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Include Help Socket IO</title>
  </head>
  <body>
    <button onClick="sendToServer()">Hit Me</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script>
	<!-change the host if sending the message outside localhost ->
      const socket = io("http://localhost:8080");

      function sendToServer () {
        socket.emit("message", "HELLO INCLUDE HELP");
      }
      <!-to view this message hit f12 and select on console tab ->
      socket.on("message", function(data) {
  			console.log(data)
	  });

    </script>
  </body>
</html>

执行服务器代码(python3 socket_io_server.py)

    (venv) -bash-4.2$ python3 socket_io_server.py
    ======== Running on http://0.0.0.0:8080 ========
    (Press CTRL+C to quit)

在浏览器中,打开:http:// localhost:8080

python中的websocket实现

服务器日志

    socket id is a5c3c73715fc4e9380477daf56f26fe2
    HELLO INCLUDE HELP

并在客户端(浏览器)

python输出中的websocket实现