未找到套接字IO(404)

时间:2016-01-13 23:33:53

标签: javascript node.js sockets websocket socket.io

嗨我在使用socket io工作时遇到了一些问题。问题是当我想从我当地的apache服务器上的网站上调用chatDiv.html时

我的节点js服务器名为index.js

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

app.use(function (req, res, next) {

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost');

// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);

// Pass to next layer of middleware
next();
});

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

io.on('connection', function(socket){
console.log('a user connected');
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
    console.log(msg);
  });
});

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

服务器加载的客户端文件是chatDiv.html

<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<div class="chat body">
<ul style="width:100%;height:100px;" id="messages"></ul>

<input style="width:100px;height:20px"id="m" autocomplete="off">  </input><button id="sendM"   >Send</button>

</div>

最后我想从我的apache服务器与socket io进行交互我这样做是通过将chatDiv.html的内容加载到这样的容器中来实现的

<script src="http://localhost:3000/socket.io/socket.io.js"></script>
$( document ).ready(function() {
$("#chatContainer").load("http://localhost:3000/", function() {
  console.log('loaded chatdiv');
  var socket = io();
  $( "#chatContainer" ).on( "click", "#sendM", function() {
console.log('clicked');
}); 
}); 
});

现在chatDiv的内容正被加载到我的网站,我可以看到正在加载的套接字io文件。但是在打电话时会出错 var socket = io();

GET http://localhost/socket.io/?EIO=3&transport=polling&t=L8zL8x0 404 (Not Found)

1 个答案:

答案 0 :(得分:0)

您能具体说明您遇到的错误吗?您可能希望在io()周围包装一个try-catch块,以查看它是否为您提供了任何提示。我怀疑它与您的端口访问权限或防火墙设置有关。

示例:

$( document ).ready(function() {
    $("#chatContainer").load("http://localhost:3000/", function() {
        console.log('loaded chatdiv');
        try{
           var socket = io();
        }
        catch(e){
           //log the error here
           console.log(e);
        }
        $( "#chatContainer" ).on( "click", "#sendM", function() {
            console.log('clicked');
        }); 
    }); 
});