Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

node.js - Can't connect to Socket.io nodejs server

This is the code of the Server:

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

http = http.createServer(app).listen(3400,() => {
    var io = require('socket.io')(http);
    io.on('connection', (socket) => {
        console.log('connection');
    });
});

I am using the Socket.io Client Test Tool: https://amritb.github.io/socketio-client-tool/

When I enter the address http://myWANIP:3400 as the URL and hit connect, nothing happens.

What am I doing wrong?

Any help is much appreciated :D

Edit: The Host is behind a NAT and the port 3400 is being forwarded (TCP).

Edit2: After some helpful comments I changed the code to:

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

var server = http.createServer(app).listen(3400);

var io = require('socket.io')(server);

io.on('connection', (socket) => {
    console.log('connection');
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your second code block looks more appropriate. We can't really tell if your NAT and port forwarding is set up correctly, but if it is, then you should be able to make a socket.io connection from a web page with this:

<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io("http://myWANIP:3400", {transports: ["webSocket"]});
</script>

And, when that connection occurs, you should see the results of console.log('connection'); in the server logs.

Another way to verify that your NAT and port forwarding is working correctly is to add this to your server:

app.get("/", (req, res) => {
     console.log("got web page request");
     res.send("hello");
});

Then, when you got to http://myWANIP:3400, in the browser, you should get a log on your server and a response page back that says "hello".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...