首页 > 解决方案 > 使用 python 和 Typscript 连接两个套接字(客户端和服务器)

问题描述

问题

我在连接两个套接字时遇到问题。关系是客户端和服务器(单连接)。

我有的

我能够使用 python3 成功运行我的服务器,并且还能够成功托管连接套接字的 Angular 应用程序,但是当我尝试发出事件或从我的 Angular 代码连接时,在握手期间出现 400 错误,python 上的错误服务器端看起来像这样

客户端正在使用不受支持的 Socket.IO 或 Engine.IO 协议版本(此错误的进一步发生将使用级别 INFO 记录)

我希望能够做什么 连接到服务器并让它发送一个 json 有效负载和以后的视频源。

Python3 代码

import eventlet
import socketio

sio = socketio.Server(cors_allowed_origins='*')

app = socketio.WSGIApp(sio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'index.html'}
})


@sio.on('sensorframe')
def message(sid, data):
    print('message ', data)

@sio.event
def controller(command: str):
    print(command)

if __name__ == '__main__':
    eventlet.wsgi.server(eventlet.listen(('127.0.0.1', 8010)), app)

python-socketio 版本 = 5.0.4

import * as io from 'socket.io-client';

export class GuagesComponent implements OnInit {
  private sensorframe: object;
  public socket: SocketIOClient.Socket;

  constructor(
    private ref: ChangeDetectorRef,
    private _socketService: SocketsService
  ) {
    this.socket = io.connect('http://127.0.0.1:8010', {
      reconnection: true,
      reconnectionDelay: 5000,
      reconnectionDelayMax: 5000,
      reconnectionAttempts:  5,
      transports: ['websocket', 'polling', 'flashsocket', 'xhr-polling'],

    });
    console.log(io.protocol); // 4
  }

  private eventFire(): void {
   this.socket.emit('controller', 'data from client');
  }

  public ngOnInit(): void {

  }
}

日志输出

python3 server.py 
(149348) wsgi starting up on http://127.0.0.1:8010
(149348) accepted ('127.0.0.1', 51348)
The client is using an unsupported version of the Socket.IO or Engine.IO protocols (further occurrences of this error will be logged with level INFO)
127.0.0.1 - - [15/Jan/2021 17:58:38] "GET /socket.io/?EIO=3&transport=websocket HTTP/1.1" 400 195 0.000308
(149348) accepted ('127.0.0.1', 51392)

标签: python-3.xangularsocketssocket.io

解决方案


归结为版本。Socket IO 客户端在前端很好,但我不得不将这个版本用于 python3

engineio==3.13.2 和 python-socketio==4.6.0


推荐阅读