首页 > 解决方案 > Socketio 未在本地主机上的邮递员套接字连接 ui 上连接

问题描述

Could not connect to localhost:3000
17:02:53
Error: Unexpected server response: 404
Handshake Details
Request URL: http://localhost:3000/socket.io/?EIO=3&transport=websocket
Request Method: GET
Status Code: 404 Not Found

我的快速服务器在 3000 端口和 443 端口上侦听 socketio http,我可以通过在 ec2 实例上托管它并在邮递员套接字连接 ui 上使用带有端口号的 ec2 ip 来连接套接字,但是在 localhost 连接上总是失败,邮递员出现上述错误套接字测试版用户界面。

标签: node.jssslsocket.iopostmanlocalhost

解决方案


您只需调用listen一次。如果你通过你的http/https服务器来表达,app.listen()就足够了。(除非你想在 2 个不同的端口上监听。为了测试,我们只调用一次。)

要访问它,请尝试使用in 中localhost的参数显式设置它。hostnameapp.listen()

例子:

async function startServer() {
  const app = express();

  const credentials = {key: key, cert: crt};
  const httpsServer = createServer(credentials,app);
  const io = socketIO(httpsServer);
  
  await require('./loaders').default({ expressApp: app, socketIO: io });

  // Let's only call listen once for testing purposes. If you call 
  // listen on the express app, your https server will automatically listen 
  // to the same configuration.
  // httpsServer.listen(4000);

  
 
  const port = 3000
  const hostname = 'localhost'
  // explicitly let the app listen on localhost. If hostname is not 
  // provided, it will take the first found ipv4 interface
  app.listen(port, hostname, err => {
    if (err) {
      Logger.error(err);
      process.exit(1);
      return;
    }
    Logger.info(`
      ################################################
      ️  Server listening on https://${hostname}:${port} ️ 
      ################################################
    `);
  });

}

现在你应该可以连接你的套接字了。如果它仍然不起作用,请尝试使用http模块而不是https更好地隔离您的问题。

请注意,您的服务器现在只能使用localhost而不是通过 ip 访问。两者都可能仅在运行具有不同主机名的 2 个服务器实例时才有可能。


推荐阅读