【问题标题】:Node.js server is not working properlyNode.js 服务器无法正常工作
【发布时间】:2012-01-20 13:38:54
【问题描述】:

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

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) 上

【问题讨论】:

  • 可以分享客户端脚本吗?您必须在客户端加载socket.io js文件。
  • 如果我在日志中看到“info - socket.io started”,这意味着 socket.io 加载了吗?我使用此示例中的 Flash 客户端 github.com/simb/FlashSocket.IO
  • 好吧,我知道 socket.io 必须在客户端包含一个 javascript 文件(html 文件),以便浏览器知道服务器正在尝试与之交互。有关 cpl 示例,请参阅 psitsmike.com。所以我猜你也需要闪光灯插座。
  • 谢谢迈克。在这个例子中我没有找到其他的 js,可能也不需要它们,因为 Flashsockets 可以直接与服务器一起工作——它可以在控制台日志中看到。问题可能出在其他地方,并且可能是 Windows 7。我也无法运行分发 Socket.IO 附带的常用聊天示例。这很奇怪,但我可以运行我在网上找到的其他文本聊天示例。很奇怪……
  • 迈克,我试试你的例子 (psitsmike.com/2011/09/node-js-and-socket-io-chat-tutorial),它工作正常。但我需要 Flash 客户端...

标签: javascript node.js websocket socket.io


【解决方案1】:

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

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

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 2015-03-06
    • 1970-01-01
    • 2013-03-22
    • 2017-06-02
    • 2015-10-27
    • 2016-12-30
    相关资源
    最近更新 更多