python - 从 Electron UI 连接套接字到 python 服务器时出现错误 400(错误请求)

标签 python node.js sockets websocket electron

我在使用 Web 套接字连接 Electron 和 Python 时遇到了一些问题(主要是作为学习体验):

  • 使用 Electron 构建桌面应用好的

  • 构建一个监视某些事情的Python程序好的

  • 使用 socket.io 连接 Python 和 Electron 不工作

首先,我使用 https://github.com/miguelgrinberg/python-socketio/tree/master/examples/server/aiohttp 中的“延迟”示例在 python 中测试了 socket.io 。当我查看 http://localhost:8080/ 时效果很好在 Chrome 中。

下一步是要求 Electron 在桌面应用程序中加载相同的 URL mainWindow.loadURL('http://localhost:8080') (我使用了官方electron-quick-start示例中的模板)。我只需在 html 中添加两行,如下所示:Electron: jQuery is not defined让 jquery 在 Electron 中正确加载,但它再次运行良好。

现在我尝试创建一个 index.htmllatency.html 内容相同并加载 mainWindow.loadFile('gui/index.html') 。我改变了线路 var socket = io.connect();对于 var socket = io.connect('ws://localhost:8080'); (我也尝试过 ws://127.0.0.1:8080ws://192.168.<x>.<x>:8080 )。 html 文件正确加载,但套接字开始重复连接和断开连接,并出现错误请求错误(我添加了两行 console.log 行):

(console.log) connected
(error)       POST http://localhost:8080/socket.io/?EIO=3&transport=polling&t=MosNuF3&sid=c62ce5a6090c4b72bf3f7c6916da6ce7 400 (Bad Request)   **polling-xhr.js:264**
(console.log) disconnected
(warning)     websocket.js:235 WebSocket connection to 'ws://localhost:8080/socket.io/?EIO=3&transport=websocket&sid=c62ce5a6090c4b72bf3f7c6916da6ce7' failed: WebSocket is closed before the connection is established.
(error)       POST http://localhost:8080/socket.io/?EIO=3&transport=polling&t=MosNuFS&sid=c62ce5a6090c4b72bf3f7c6916da6ce7 400 (Bad Request)   **polling-xhr.js:264**
(console.log) connected
etc...
(console.log) disconnected
etc...

在服务器端,当我停止 Electron 应用程序时也出现错误:

Unhandled exception
Traceback (most recent call last):
  File "D:\Programming\Tools\Anaconda3\lib\site-packages\aiohttp\web_protocol.py", line 447, in start
    await resp.prepare(request)
  File "D:\Programming\Tools\Anaconda3\lib\site-packages\aiohttp\web_response.py", line 353, in prepare
    return await self._start(request)
  File "D:\Programming\Tools\Anaconda3\lib\site-packages\aiohttp\web_response.py", line 667, in _start
    return await super()._start(request)
  File "D:\Programming\Tools\Anaconda3\lib\site-packages\aiohttp\web_response.py", line 410, in _start
    await writer.write_headers(status_line, headers)
  File "D:\Programming\Tools\Anaconda3\lib\site-packages\aiohttp\http_writer.py", line 112, in write_headers
    self._write(buf)
  File "D:\Programming\Tools\Anaconda3\lib\site-packages\aiohttp\http_writer.py", line 67, in _write
    raise ConnectionResetError('Cannot write to closing transport')
ConnectionResetError: Cannot write to closing transport

此错误请求错误在此上下文中意味着什么?连接如何正确工作?

谢谢。

最佳答案

如果有人遇到同样的问题。答案非常简单,来自 socket.io here 的文档:

For security reasons, this server enforces a same-origin policy by default. In practical terms, this means the following:

  • If an incoming HTTP or WebSocket request includes the Origin header, this header must match the scheme and host of the connection URL. In case of a mismatch, a 400 status code response is returned and the connection is rejected.
  • No restrictions are imposed on incoming requests that do not include the Origin header.

If necessary, the cors_allowed_origins option can be used to allow other origins. This argument can be set to a string to set a single allowed origin, or to a list to allow multiple origins. A special value of '*' can be used to instruct the server to allow all origins, but this should be done with care, as this could make the server vulnerable to Cross-Site Request Forgery (CSRF) attacks.

当使用 Electron 加载 gui 时,服务器与执行监控的 python 服务器不同,因此会出现错误请求(不是同源)。解决方案是只需修改服务器属性,添加 cors_allowed_origins='*':

socketio.AsyncServer(async_mode='aiohttp', cors_allowed_origins='*')

关于python - 从 Electron UI 连接套接字到 python 服务器时出现错误 400(错误请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57600153/

相关文章:

python - 将 spark DataFrame 列转换为 python 列表

c++ - 开放框架 + Python

javascript - 当我使用 axios POST 时,Req.body 为空,但当我使用 'request' 时,它工作正常

java - 在 JavaFx 中管理至少三个线程

javascript - 简单的实时网络应用程序用作 'voting terminal'

java - 使用密码时 SSL 库失败

python - 使用 py2 解释器时 PyCharm py3 语法问题

python - asyncio.sleep 的行为就像一个拦截器

javascript - 你如何检测 typeorm 中的密码等属性是否已更改

node.js - Uglify Minify 并使用 Gulp 生成 source map