socket.io 无法使用静态文件路由 node.js

socket.io is not working with static file routing node.js

我正在编写一个聊天应用程序。在那里,当静态文件路由正常工作时 socket.io (Chat) is not working throws not found error in console.

http://localhost/socket.io/?EIO=3&transport=polling&t=1486739955177-8 404 not found

当聊天正常时 public 静态文件不工作会抛出错误

Cannot GET /public/index.html

代码聊天有效(public 静态文件无效):

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

//Initialize application with route
app.get('/',function (req,res) {
 var express=require('express');
 app.use(express.static(path.join(__dirname+'/public')));
 res.sendFile(path.join(__dirname,'../public','chat.html'));
});

//Register events on socket connection
io.on('connection',function (socket) {
   socket.on('chatMessage',function (from, msg) {
    io.emit('chatMessage',from,msg);
 });

 socket.on('notifyUser',function (user) {
    io.emit('notifyUser',user);
  });
});

// Listen appliaction request on port 80
http.listen(80,function () {
   console.log('Server Running in port 80');
});

代码 public 静态文件有效(聊天无效):

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

//Initialize application with route
var express=require('express');
app.use(express.static('public/'));
app.use('/public',express.static('public/stack'));


//Register events on socket connection
io.on('connection',function (socket) {
    socket.on('chatMessage',function (from, msg) {
        io.emit('chatMessage',from,msg);
    });
    socket.on('notifyUser',function (user) {
        io.emit('notifyUser',user);
    });
});


app.get('*', function(req, res){
    res.send('what???', 404);
});

// Listen appliaction request on port 80
app.listen(80,function () {
    console.log('Server Running in port 80');
}

好的,这段代码有效

var express=require('express');
var app = express();
var path=require('path');
var server = require('http').createServer(app);
var io=require('socket.io')(server);
//Initialize application with route
app.use(express.static('public/'));
// app.use('/public',express.static('public/stack'));

//Register events on socket connection
io.on('connection',function (socket) {
    socket.on('chatMessage',function (from, msg) {
        io.emit('chatMessage',from,msg);
    });
    socket.on('notifyUser',function (user) {
        io.emit('notifyUser',user);
    });
});

app.get('/', function(req, res){
    res.send('what???', 404);
});

// Listen appliaction request on port 80
server.listen(80,function () {
    console.log('Server Running in port 80');
});

将您的 chat.html 移动到 public 文件夹中,然后像 http://localhost/client.html

一样访问

目录结构如

appdir public/client.html server.js node server.js