如何不使用本地主机,而是使用服务器的 IP?

1 amazon-ec2 amazon-web-services node.js socket.io

我在本教程中找到了这个节点应用程序并想使用它,但它被配置为作为本地主机运行。由于该应用程序在 Amazon Linux EC2 上运行,因此无法对其进行桌面(本地)访问(也许需要安装软件以启用桌面模式,但我还没有)。

我想在服务器上运行应用程序,而不是在本地主机上,而是在服务器的弹性 IP 地址上运行,我将添加到我的域 chatxs.com 的托管区域。

我想让应用程序侦听此 IP 中的任何请求,该 IP 将再次位于域名的 DNS 中。

这是教程附带的代码,我唯一更改的是视图文件夹中的 .html 文件(样式、对齐和一些文本,应用程序没有代码更改,只有 html):

应用程序.js

// This is the main file of our chat app. It initializes a new 
// express.js instance, requires the config and routes files
// and listens on a port. Start the application by running
// 'node app.js' in your terminal

var express = require('express'),
    app = express();

// This is needed if the app is run on heroku:

var port = process.env.PORT || 8080;

// Initialize a new socket.io object. It is bound to 
// the express app, which allows them to coexist.

var io = require('socket.io').listen(app.listen(port));
// Require the configuration and the routes files, and pass
// the app and io as arguments to the returned functions.

require('./config')(app, io);
require('./routes')(app, io);

console.log('Your application is running on http://localhost:' + port);
Run Code Online (Sandbox Code Playgroud)

配置文件

// This file handles the configuration of the app.
// It is required by app.js

var express = require('express');

module.exports = function(app, io){

// Set .html as the default template extension
app.set('view engine', 'html');

// Initialize the ejs template engine
app.engine('html', require('ejs').renderFile);

// Tell express where it can find the templates
app.set('views', __dirname + '/views');

// Make the files in the public folder available to the world
app.use(express.static(__dirname + '/public'));

};
Run Code Online (Sandbox Code Playgroud)

routes.js太大了,无法在此处对其进行格式化。

最后

包.json

{
"name": "NodeChatSystem",
"version": "0.0.1",
"description": "Realtime chat system for Tutorialzine.com",
"main": "app.js",
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
  "node",
  "chat",
  "system"
],
"author": "Nikolay Anastasov",
"license": "MIT",
"dependencies": {
  "ejs": "^1.0.0",
  "express": "^4.8.2",
  "gravatar": "~1.0.6",
  "socket.io": "^1.0.6"
  }
}
Run Code Online (Sandbox Code Playgroud)

以上基本上是教程 .zip 文件中包含的内容。

Mat*_*ser 5

当您简单地使用 时app.listen(port),它将只允许来自 localhost 的连接(如您所见)。

要允许外部连接,请使用app.listen(port, "0.0.0.0"). 这告诉 Node 侦听外部网络接口。

此外,请确保您的 EC2 实例的安全组允许在适当端口上的传入连接。

更新:

正如 jfriend00 所指出的,并进一步调查,这是不正确的。

参考:http : //expressjs.com/api.html#app.listen

  • 这是不正确的。`app.listen(port)` 不限制连接只能来自本地主机。我有一个运行 `app.listen(port)` 的服务器,它接受来自我网络上任何主机的连接。 (4认同)