未处理的socket.io URL错误

时间:2015-08-13 17:44:41

标签: node.js socket.io

编辑2:在使用robertklep的建议之后我仍然得到信息 - 未处理的socket.io url错误,但我现在也得到“GET /socket.io/socket.io.js 404 3.325 ms - 1257”现在

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
    at ServerResponse.header (/Users/actuallywilliam/Desktop/Work/Websites/Click the Button/node_modules/express/lib/response.js:718:10)
    at ServerResponse.contentType (/Users/actuallywilliam/Desktop/Work/Websites/Click the Button/node_modules/express/lib/response.js:551:15)
    at ServerResponse.send (/Users/actuallywilliam/Desktop/Work/Websites/Click the Button/node_modules/express/lib/response.js:138:14)
    at done (/Users/actuallywilliam/Desktop/Work/Websites/Click the Button/node_modules/express/lib/response.js:957:10)
    at View.exports.renderFile [as engine] (/Users/actuallywilliam/Desktop/Work/Websites/Click the Button/node_modules/ejs/lib/ejs.js:355:10)
    at View.render (/Users/actuallywilliam/Desktop/Work/Websites/Click the Button/node_modules/express/lib/view.js:126:8)
    at tryRender (/Users/actuallywilliam/Desktop/Work/Websites/Click the Button/node_modules/express/lib/application.js:639:10)
    at EventEmitter.render (/Users/actuallywilliam/Desktop/Work/Websites/Click the Button/node_modules/express/lib/application.js:591:3)
    at ServerResponse.render (/Users/actuallywilliam/Desktop/Work/Websites/Click the Button/node_modules/express/lib/response.js:961:7)

编辑结束

我正在this上尝试my website教程,但我遇到了这个错误:

info  - unhandled socket.io url

我正在使用Socket.io版本0.9.10(因为它说在教程中使用该版本)。

这是我的HTML:          

    <meta charset="utf-8" />
    <title>Draw</title>

    <!-- The stylesheets -->
    <link rel="stylesheet" href="../assets/css/styles.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

    <!--[if lt IE 9]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>

<body>
  <div id="body">
    <center>
        <h1>Draw <a href="draw-changelog" id="version">Indev</a></h1>
            <p><a id="tip">tip</a>: refresh the page to clear the canvas!</p>
          <p>made by <a href="aboutme">William</a> - <a href="https://twitter.com/williamsthing">@williamsthing</a> / <a href="https://ello.co/972">@972</a>. inspired by <a href="http://flockdraw.com">flockdraw</a>. <a id="version" href="draw-changelog">v1.0</a>.</p>
        </center>
    </div>
    <div id="cursors">
        <!-- The mouse pointers will be created here -->
    </div>

    <canvas id="paper" width="1900" height="1000">
        Your browser needs to support canvas for this to work!
    </canvas>


    <!--<script src="socketio/node_modules/socket.io-client/dist/socket.io.js"></script> !-->
    <script src="socketio/node_modules/socket.io-client/dist/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
    <script id="drawing" src="../assets/js/script.js"></script>

</body>

这是我的script.js:

$(function(){

// This demo depends on the canvas element
if(!('getContext' in document.createElement('canvas'))){
    alert('Sorry, it looks like your browser does not support canvas!');
    return false;
}

// The URL of your web server (the port is set in app.js)
var url = 'http://localhost:8080';

var doc = $(document),
    win = $(window),
    canvas = $('#paper'),
    ctx = canvas[0].getContext('2d'),
    instructions = $('#instructions');

// Generate an unique ID
var id = Math.round($.now()*Math.random());

// A flag for drawing activity
var drawing = false;

var clients = {};
var cursors = {};

var socket = io.connect();

socket.sockets.on('moving', function (data) {

    if(! (data.id in clients)){
        // a new user has come online. create a cursor for them
        cursors[data.id] = $('<div class="cursor">').appendTo('#cursors');
    }

    // Move the mouse pointer
    cursors[data.id].css({
        'left' : data.x,
        'top' : data.y
    });

    // Is the user drawing?
    if(data.drawing && clients[data.id]){

        // Draw a line on the canvas. clients[data.id] holds
        // the previous position of this user's mouse pointer

        drawLine(clients[data.id].x, clients[data.id].y, data.x, data.y);
    }

    // Saving the current client state
    clients[data.id] = data;
    clients[data.id].updated = $.now();
});

var prev = {};

canvas.on('mousedown',function(e){
    e.preventDefault();
    drawing = true;
    prev.x = e.pageX;
    prev.y = e.pageY;

    // Hide the instructions
    instructions.fadeOut();
});

doc.bind('mouseup mouseleave',function(){
    drawing = false;
});

var lastEmit = $.now();

doc.on('mousemove',function(e){
    if($.now() - lastEmit > 30){
        socket.emit('mousemove',{
            'x': e.pageX,
            'y': e.pageY,
            'drawing': drawing,
            'id': id
        });
        lastEmit = $.now();
    }

    // Draw a line for the current user's movement, as it is
    // not received in the socket.on('moving') event above

    if(drawing){

        drawLine(prev.x, prev.y, e.pageX, e.pageY);

        prev.x = e.pageX;
        prev.y = e.pageY;
    }
});

// Remove inactive clients after 10 seconds of inactivity
setInterval(function(){

    for(ident in clients){
        if($.now() - clients[ident].updated > 10000){

            // Last update was more than 10 seconds ago.
            // This user has probably closed the page

            cursors[ident].remove();
            delete clients[ident];
            delete cursors[ident];
        }
    }

},10000);

function drawLine(fromx, fromy, tox, toy){
    ctx.moveTo(fromx, fromy);
    ctx.lineTo(tox, toy);
    ctx.stroke();
}

});

最后,这是我的app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');
var cors = require('cors')

var app = express();
var app_serv = require('http').createServer(handler),
  io = require('socket.io').listen(app_serv),
  static = require('node-static'); // for serving files


  var allowCrossDomain = function(req, res, next) {
      res.header('Access-Control-Allow-Origin', "*");
  };

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/socketio', express.static(__dirname + '/node_modules/socket.io'));

app.use('/', routes);
app.use('/users', users);
app.use(cors());

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});




module.exports = app;


// This will make all the files in the current folder
// accessible from the web
var fileServer = new static.Server('./');

// This is the port for our web server.
// you will need to go to http://localhost:8080 to see it
app_serv.listen(8080);

// If the URL of the socket server is opened in a browser
function handler (request, response) {

  request.addListener('end', function () {
        fileServer.serve(request, response);
    });
}

// Listen for incoming connections from clients
io.sockets.on('connection', function (socket) {

  // Start listening for mouse move events
  socket.on('mousemove', function (data) {

    // This line sends the event (broadcasts it)
    // to everyone except the originating client.
    socket.broadcast.emit('moving', data);
  });
    });

编辑:我也在控制台中获得这一行:     GET /socket.io/1/?t=1439497344004 404 6.084 ms - 1257 我也可能需要帮助。

1 个答案:

答案 0 :(得分:1)

您的应用设置有问题,您似乎正在混合Express和非Express部件。

要设置Express应用,请使用以下命令:

app_serv

并删除与fileServerapp.use('/socketio', express.static(__dirname + '/node_modules/socket.io')); 相关的所有内容,因为您不需要它。

同时删除此内容:

<script src="socketio/node_modules/socket.io-client/dist/socket.io.js"></script>

改变这个:

<script src="/socket.io/socket.io.js"></script>

对此:

var App = angular.module('MyApp', ['MyApp.filters', 'MyApp.services', 'MyApp.directives', 'ui.bootstrap']);