gpt4 book ai didi

javascript - 无法从外部连接到 Node.js/Socket.io/Express 服务器

转载 作者:行者123 更新时间:2023-12-03 05:02:59 24 4
gpt4 key购买 nike

因此,我尝试从外部互联网(而不是本地网络)连接到我使用 Node.js、Socket.io 和 Express 创建的服务器。这是我的代码:

服务器:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});

http.listen(3000,function(){
console.log('listening on *:3000');
});

客户:

<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>

我有端口转发端口3000。http://localhost:3000/有效,连接同一网络上的其他计算机也有效,但我得到了我的外部IP:12.888.999.12(随机IP)。我也有我的端口 3000。当我在 google chrome 中连接 http://12.888.999.12:3000不起作用。

最佳答案

当你说外部IP时,这是否意味着你已经在某处购买了云服务器或其在内网中。你使用的是哪个操作系统?服务器计算机上的端口 3000 是否开放?

例如。如果它是 Windows 计算机,您需要转到具有高级安全性的 Windows 防火墙并打开 TCP 访问的入站端口

如果你已经这样做了,那么试试这个::

http.listen(3000, '0.0.0.0', function() {
console.log('Listening to port: ' + 3000);
});

然后尝试使用http://12.888.999.12:3000访问

关于javascript - 无法从外部连接到 Node.js/Socket.io/Express 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42141522/

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