【问题标题】:Listen on specific url instead of port监听特定的 url 而不是端口
【发布时间】:2014-12-18 14:55:36
【问题描述】:

我对 Nodejs 完全陌生,并试图熟悉它。 好吧,目前,如果数据库中发生任何更改,我正在尝试在 Web 浏览器上推送通知。我有一段代码,我首先将其用于测试目的。以下代码可以在数据库表内容更改时向浏览器发送更新:

Server.js

var app = require('http').createServer(handler).listen(8000),
  io = require('socket.io').listen(app),
  fs = require('fs'),
  mysql = require('mysql'),
  connectionsArray = [],
  connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'nodejs',
    port: 3306
  }),
  POLLING_INTERVAL = 3000,
  pollingTimer,
  pollingTimer_2;


// If there is an error connecting to the database
connection.connect(function(err) {
  // connected! (unless `err` is set)
  console.log(err);
});


// on server started we can load our client.html page
function handler(req, res) {
  fs.readFile(__dirname + '/client.html', function(err, data) {
    if (err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error loading client.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}




/*
 * This function loops on itself since there are sockets connected to the page
 * sending the result of the database query after a constant interval
 *
 */

var pollingLoop = function() {

  // Doing the database query
  var query = connection.query('SELECT * FROM users'),
    users = []; // this array will contain the result of our db query

  // setting the query listeners
  query
    .on('error', function(err) {
      // Handle error, and 'end' event will be emitted after this as well
      console.log(err);
      updateSockets(err);
    })
    .on('result', function(user) {
      // it fills our array looping on each user row inside the db
      users.push(user);
    })
    .on('end', function() {
      // loop on itself only if there are sockets still connected
      if (connectionsArray.length) {
        pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);

        updateSockets({
          users: users
        });
      }
    });

};


// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {

  console.log('Number of connections:' + connectionsArray.length);
  // starting the loop only if at least there is one user connected
  if (!connectionsArray.length) {
    pollingLoop();

  }

  socket.on('disconnect', function() {
    var socketIndex = connectionsArray.indexOf(socket);
    console.log('socket = ' + socketIndex + ' disconnected');
    if (socketIndex >= 0) {
      connectionsArray.splice(socketIndex, 1);
    }
  });

  console.log('A new socket is connected!');
  connectionsArray.push(socket);

});

var updateSockets = function(data) {
  // adding the time of the last update
  data.time = new Date();
  // sending new data to all the sockets connected
  connectionsArray.forEach(function(tmpSocket) {
    tmpSocket.volatile.emit('notification', data);
  });
};

Client.html

<html>
    <head>

        <title>Push notification server streaming on a MySQL db</title>
        <style>
            dd,dt {
                float:left;
                margin:0;
                padding:5px;
                clear:both;
                display:block;
                width:100%;

            }
            dt {
                background:#ddd;
            }
            time {
                color:gray;
            }
        </style>
    </head>
    <body>
        <time></time>
        <div id="container">Loading ...</div>
    <script src="socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>

        // create a new websocket
        var socket = io.connect('http://localhost:8000');
        // on message received we print all the data inside the #container div
        socket.on('notification', function (data) {
        var usersList = "<dl>";
        $.each(data.users,function(index,user){
            usersList += "<dt>" + user.user_name + "</dt>\n" +
                         "<dd>" + user.user_desc + "\n" +
                            "<figure> <img class='img-polaroid' width='50px' src='" + user.user_img + "' /></figure>"
                         "</dd>";
        });
        usersList += "</dl>";
        $('#container').html(usersList);

        $('time').html('Last Update:' + data.time);
      });
    </script>
    </body>
</html>

现在,您可以看到当前服务器正在侦听port 8000。我只是想知道如何更改它以收听特定的网址?因为如果我要在服务器项目上实现,那么我不会使用 url 来监听端口?相反,我想将它用作普通的 Url,因为如果有任何用户连接到特定的 url,我可以顺利地发送通知?

有什么帮助吗?

【问题讨论】:

  • 服务器不监听 URL。它们在给定端口上侦听给定 IP 地址。你无法改变这一点。如果您的意思是您不想在 URL 中输入端口号,那么您希望您的服务器侦听端口 80(默认的 http 端口)。未与 URL 建立连接。它针对给定服务器上的给定端口,然后在连接后将 URL 的路径作为数据传递。
  • 我不明白我将如何应用于特定 url 上的推送通知?假设我有以下链接,用户登录http://www.example.com/updates。现在,如果数据库发生任何更改,我如何在此链接上发送更新?在当前情况下,它会是这样的:http://www.example.com:8000/updates .
  • 你让你的服务器监听端口 80,你让你的节点服务器响应路径/updates。这就是你连接http://www.example.com/updates 的方式。如果 URL 中没有端口号且协议为http,则端口默认为端口 80。
  • 好的。感谢您的信息。我会尝试:)

标签: node.js push-notification


【解决方案1】:

如果您希望您的节点服务器响应 URL http://www.example.com/updates,那么您让您的服务器侦听端口 80(如果没有列出端口并且协议为“http”,则为默认端口)。然后,让你的服务器响应"/updates" 路由。

服务器侦听特定 IP 地址的特定端口。他们不听路径或 URL。浏览器使用 DNS 获取 URL 中主机的 IP 地址。如果 URL 中有端口号,它将使用该端口。如果不是,它使用特定协议的默认端口。然后,它会在该端口上与该 IP 地址建立 TCP 连接。然后,如果协议是 http,它会在该连接上发送一个请求并包含路径。

因此,服务器接收传入的连接,然后作为 HTTP 协议的一部分,它接收动词(GET、POST、DELETE 等...)和路径,然后服务器将决定要做什么根据传入的命令/路径执行。

【讨论】:

  • 好吧,我试过你的方法,但它弹出了EADDRINUSE。这是因为我的 apachi 也在同一个端口上运行。因此,只是想知道如何避免这种情况?
  • 正确的方法显然是使用不同的端口。但是我很幸运地使用了不同的本地主机环回 IP 地址(127.0.0.5)和 express(express().listen(80, '127.0.0.5'))而不是 http。
  • @Princess - 对于给定的 IP 地址,每个端口只能有一个侦听器。您要么需要使用不同的 IP 地址(这通常意味着不同的服务器,除非在一个盒子上进行多网络连接)或不同的端口,或者将 express 和 apache 服务器的功能组合到一个服务器中。
猜你喜欢
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多