[英]Using an IP address parameter in the creation of a Socket.io socket
In the following snippet, a tutorial author shows how to alter the original tutorial to include an http server. 在以下代码段中,教程作者展示了如何更改原始教程以包括http服务器。 Here's the snippet.
这是代码段。
var http = require(‘http’),
fs = require(‘fs’),
io = require(‘socket.io’),
index;
fs.readFile(‘./chat.html’, function (err, data) {
if (err) {
throw err;
}
index = data;
});
var server = http.createServer(function(request, response) {
response.writeHeader(200, {“Content-Type”: “text/html”});
response.write(index);
response.end();
}).listen(1223);
//and replace var socket = io.listen(1223, "1.2.3.4"); with:
var socket = io.listen(server);
The code in the original tutorial didn't include the http server, and socket
was defined as simply: 原始教程中的代码不包含http服务器,
socket
定义很简单:
var socket = io.listen(1223, "1.2.3.4");
I noticed that he replaces the variable's content io.listen(1223, "1.2.3.4");
我注意到他替换了变量的内容
io.listen(1223, "1.2.3.4");
with server
which doesn't include the ip ( 1.2.3.4
) anywhere. 与不包含ip(
1.2.3.4
)的server
。
My Question: 我的问题:
When you are listening on a port, you can optionally include the IP address of a specific interface to listen on. 在侦听端口时,可以选择包括要侦听的特定接口的IP地址。 For example, you might have several network interfaces with several IP addresses, and only want your service running on one of them.
例如,您可能有几个带有多个IP地址的网络接口,而只希望您的服务在其中之一上运行。 A more common use case is that you only want your server accessible on localhost, so you might have it listen only on
127.0.0.1
. 一个更常见的用例是,您只希望服务器可以在localhost上访问,因此您可能只让它在
127.0.0.1
上侦听。
Now, when you call io.listen(server)
where server
is an existing Node.js HTTP server, Socket.IO isn't actually opening a new listening connection at all. 现在,当您调用
io.listen(server)
,其中server
是现有的Node.js HTTP服务器时,Socket.IO实际上根本没有打开新的侦听连接。 This is a shortcut for Socket.IO to wrap its methods on the existing HTTP server. 这是Socket.IO将其方法包装在现有HTTP服务器上的快捷方式。 If you wanted to specify a specific interface address to listen on, you would need to do it where
.listen()
is called on the HTTP server, above where you call io.listen(server)
. 如果你想指定一个特定接口地址监听,你需要做的是在那里
.listen()
被称为HTTP服务器上,上面,你叫io.listen(server)
。
More info in the documentation for raw network sockets in Node.js: http://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback 有关Node.js中原始网络套接字的文档中的更多信息: http : //nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.