0

我有一个 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 连接?我的配置有什么错误吗?因为我是软件工程的新手,所以我一直在解决这个问题。提前致谢

4

1 回答 1

0

这是正常的,你必须用“前端”打开地址。您应该能够使用以下两个文件进行连接:

索引.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>

客户端.js:

function startSocket() {
    var ws = new WebSocket("ws://localhost:8765/")
    ws.onopen = function(event) {
        ws.send("Sent this from client.js")
    }
}
startSocket();
于 2020-04-30T17:40:43.170 回答