gpt4 book ai didi

javascript - 如何在没有express的情况下在nodejs中使用网络IP而不是localhost?

转载 作者:太空宇宙 更新时间:2023-11-04 01:50:01 25 4
gpt4 key购买 nike

我使用 NodeJS 作为视频游戏的服务器,我想尝试多人游戏部分,但是我无法通过本地主机从计算机外部进行连接。

所以,我之前使用过express,这有效:
var app = express();
var serv = app.listen(8081, "127.0.0.1");
上面,服务器使用的是 localhost(127.0.0.1),但它可以更改为我想要的任何 IP。并且正在监听8081端口。

问题是,我不再使用express,只使用Nodejs。我正在“手动”处理请求、响应和处理程序。我在这里研究了一点express的文档:
http://expressjs.com/es/4x/api.html#app.use
但说实话,我不明白这个功能是如何工作的。


这是我的 server.js:

//导入必要的模块
var http = require('http');

//服务器对象
服务器 = {};

//启动http服务器
server.httpServer = http.createServer(函数(req, res){
/* 东西 */
}

//启动服务器
server.httpServer.listen(8081, 函数(){
console.log('服务器正在监听8081端口');
});

最佳答案

http.server.listen 接受要绑定(bind)的 IP 地址

参见https://nodejs.org/api/net.html#serverlistenport-host-backlog-callback

// Import the necessary modules
var http = require('http');

// Server object
server = {};

// Start the http server
server.httpServer = http.createServer(function(req, res){
/* Stuff */
}

// Start the server
server.httpServer.listen(8081, '192.168.0.1', function(){
console.log('The server is listening on port 8081');
});

关于javascript - 如何在没有express的情况下在nodejs中使用网络IP而不是localhost?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50064388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com