nginx由于无效的连接头,未能打开websocket连接:保持活力。

问题描述 投票:0回答:1

我有一个python websocket服务器,我想在nginx中提供服务。所以这是我的服务器代码。

import asyncio 
import websockets


async def recv_message(websocket, path):

    message = await websocket.recv()
    print(message)


def main():

    start_server = websockets.serve(recv_message, "localhost", 8765)

    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

if __name__ == "__main__":

    main()

这是我的nginx配置。

server{
     listen 8765;
     server_name localhost;

     location / {
     proxy_pass ws://localhost;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "Upgrade";

 }

}

当我进入 localhost:8765我从网页上收到一条信息,上面写着...。

Failed to open a WebSocket connection: invalid Connection header: keep-alive.

You cannot access a WebSocket server directly with a browser. You need a WebSocket client.

我怎么打开websocket连接? 我的配置有什么错误吗? 我一直卡在这个问题上,因为我是新的软件工程。 先谢谢你。

python nginx websocket
1个回答
0
投票

这是正常的,你必须用 "前端 "打开地址。你应该可以用这两个文件连接。

index. html:

<!DOCTYPE html><html lang="en">
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8">

  </head>
  <body>
    <script src="client.js"></script>
</body></html>

client.js:

function startSocket() {
    var ws = new WebSocket("ws://localhost:8765/")
    ws.onopen = function(event) {
        ws.send("Sent this from client.js")
    }
}
startSocket();
© www.soinside.com 2019 - 2024. All rights reserved.