Node.js服务器无法正常工作

时间:2011-12-14 19:10:18

标签: javascript node.js websocket socket.io

我正在尝试进行简单的文字聊天。服务器启动和工作。我的客户端连接正常,它显示在控制台的日志中:

C:\inetpub\wwwroot\3>node app.js
   info  - socket.io started
Socket-Chat listening on port 9202.. Go to http://<this-host>:9202
   debug - client authorized
   info  - handshake authorized 3088178251169496669
   debug - setting request GET /socket.io/1/flashsocket/3088178251169496669
   debug - set heartbeat interval for client 3088178251169496669
   debug - client authorized for
   debug - websocket writing 1::
   debug - websocket received data packet 3:::USERNAME:----------cvx
   debug - websocket received data packet 3:::xcvcx

但不要为其他聊天客户播放。

我正在尝试将服务器代码输出的不同部分插入到控制台进行测试,但它只在某些地方显示(代码“DISPLAY”),其他部分未显示(代码为“NO DISPLAY”) “)。 服务器代码app.js:

var io = require('socket.io'),
  http = require('http');

var fs = require('fs'),
  util = require('util');

var url = require('url'),
  path = require('path'),
  mime = require('mime');

function findType(uri) {
  var ext = uri.match(/\.\w+$/gi);
  if (ext && ext.length > 0) {
    ext = ext[0].split(".")[1].toLowerCase();
    return mime.lookup(ext);
  }
  return undefined;
}

function sendError(code, response) {
  response.writeHead(code);
  response.end();
  return;
}
console.log("DISPLAY");
var app = http.createServer(function(request, response) {
  var uri = url.parse(request.url).pathname;
  console.log("NO DISPLAY");
  if (uri === '/') {
    uri = '/index.html';
  } else if (uri === '/app.js') {
    sendError(404, response);
    return;
  }
  var _file = path.join(process.cwd(), uri);
console.log("NO DISPLAY");
  path.exists(_file, function(exists) {
    if (!exists) {
      sendError(404, response);
    } else {
      fs.stat(_file, function(err, stat) {
        var file = __dirname + uri,
            type = findType(uri),
            size = stat.size;
        if (!type) {
          sendError(500, response);
        }
        response.writeHead(200, {'Content-Type':type, 'Content-Length':size});
        var rs = fs.createReadStream(file);
        console.log("NO DISPLAY");
        util.pump(rs, response, function(err) {
          if (err) {
            console.log("ReadStream, WriteStream error for util.pump");
            response.end();
          }
        });
      });
    }
  });

});

// Only listen on $ node app.js

if (!module.parent) {
  app.listen(9202);
  console.log("Socket-Chat listening on port 9202.. Go to http://<this-host>:9202");
}

var socket = io.listen(app, {transports:['websocket', 'flashsocket', 'xhr-polling']}),

  buffer = [],
  MAXBUF = 1024,
  json = JSON.stringify;

var clients = [];
clients.usernames = function(client) {
    console.log("NO DISPLAY");
  return client.username;
}

socket.on('connection', function(client) {
console.log("NO DISPLAY");

  client.on('message', function(data) {
    if ((/^(USERNAME:).*$/ig).test(data)) {
      var parts = data.split(":");
      var username = parts[1];

      if (!username || username == '') {
        client.send({announcement:"You must specify a username. Please reload the app."});
        return;
      }

      var usernames = clients.map(clients.usernames);
      if (usernames.indexOf(username) >= 0) {
        client.send({announcement:"Username in use"});
        return;
      }

      client.username = username;

      client.broadcast.json.send({announcement:client.username+' joined'});
      console.log(client.sessionId + " = " + client.username);
      client.send({messages:buffer});
      client.send({userlist:usernames});
      client.send({announcement:"Connected! Hello, " + username + "!"});

      clients.push(client);
      return;
    } 

    if (!client.username) {
      client.send({announcement:"You must specify a username. Please reload the app."});
      return;
    }

    var message = {'user':client.sessionId, 'username':client.username, 'message':data};
    buffer.push(message);
    if (buffer.length > MAXBUF) {
      buffer.shift();
    }
    client.broadcast.json.send(message);
  });

  client.on('disconnect', function() {
    if (client.username) {
      client.broadcast({announcement:(client.username)+' left chat'});
    }
    var pos = clients.indexOf(client);
    if (pos >= 0) {
      clients.splice(pos, 1);
    }
  });
});

请提示此问题的可能原因。 服务器安装在Windows 7(IIS7)

1 个答案:

答案 0 :(得分:1)

我已经回答了一些关于socket.io的类似问题,试图避免复制和粘贴相同的东西:) - cf info - unhandled socket.io url

基本上API的变化很小,尝试将socket.on('connection'更改为socket.sockets.on('connection'

希望有所帮助。