Node.js 服务器工作不正常 [英] Node.js server is not working properly

查看:35
本文介绍了Node.js 服务器工作不正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a simple text chat for example. Server start and work. My client connects fine and it shows in the log of the console:

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

但是不要为聊天的其他客户端广播.

But do not get broadcast for other clients of the chat.

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

I'm trying to insert into different parts of server`s code output to the console for testing, but it is display only in some places (in code "DISPLAY"), in others not shown (in code "NO DISPLAY"). Server code 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) 上

Prompt possible causes of this problem, please. Server is installed on Windows 7 (IIS7)

推荐答案

我已经回答了一些关于 socket.io 的类似问题,尽量避免复制和粘贴相同的内容 :) - cf 信息 - 未处理的 socket.io url

I have answered some similar questions regarding socket.io, trying to avoid copying and pasting the same stuff :) - cf info - unhandled socket.io url

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

Essentially there has been a minor change in API, try changing socket.on('connection' to socket.sockets.on('connection'

希望有所帮助.

这篇关于Node.js 服务器工作不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆