在nodeJs中通过TCP连接发出问题

时间:2015-09-01 21:01:34

标签: json node.js sockets tcp

我目前正在NodeJ中进行自我训练并尝试进行简单的聊天。为此,我使用了包装' json-socket'为了在客户端和服务器之间交换json对象。 原理很简单:

  • 我启动服务器
  • 然后每个客户都必须提供一个伪
  • 完成后,它已在服务器端注册
  • 然后,当客户端发送消息时,它将被广播给所有其他客户

但我遇到了问题:

  • 让我们假设服务器已启动
  • 当第一个客户端连接时,它什么也没发生。我的意思是他没有在服务器端注册,并且没有显示服务器端的日志
  • 我终止此客户端的会话(Ctrl + c)并尝试再次连接。这次它有效,他已经注册了
  • 我推出了一个新客户端。这次他注册了4次:|
  • 我推出另一个新客户。这次他注册了9次:| :|

我只是不明白为什么。请找到以下代码......

Server.js

var net = require('net'), JsonSocket = require('json-socket');

var sockets = [];

var server = net.createServer(function(socket)
{
    server.on('connection', function(socket) { //This is a standard net.Socket
        socket = new JsonSocket(socket); //Now we've decorated the net.Socket to be a JsonSocket

        console.log('Connection');

        socket.on('message', function(message) {

            console.log("0");

            if (message.isMessage == null)
            {
                console.log("1");
                var sender = message.pseudo;

                sockets.push({socket : socket, pseudo : sender});

                sockets.forEach(function(s)
                {
                    if (s.pseudo.toString() != sender.toString())
                        s.socket.sendMessage(sender + " vient de se connecter");
                });

                console.log(sender + " vient de se connecter");
                console.log("Il y a " + sockets.length + " clients connectés");
            }
            else
            {
                console.log("2");
                var sender = message.pseudo;
                sockets.forEach(function(s)
                {
                    if (s.pseudo.toString() != sender.toString())
                    {   
                        console.log("3");
                        s.socket.sendMessage(sender + " : " + message.message);
                    }
                });
            }
        });
    });

    socket.on('error', function()
    {
        socket.emit('end');
    });

    socket.on('end', function()
    {
        // TODO : fix this part
        //sockets.slice(sockets.indexOf(socket), 1);
        console.log("Il reste " + sockets.length + " clients connectés");
    });
});

server.on('listening', function()
{
    console.log('Server launched');
});

server.listen(3000);

Client.js

var net = require('net');
var stream = require('stream');
var JsonSocket = require('json-socket');
var readable = new stream.Readable();

var port = 3000; 
var host = '127.0.0.1';
var client = new JsonSocket(new net.Socket());

// first step : pseudo init
var pseudo = '';
console.log('Give a pseudo');
readable.setEncoding('utf8');

readable._read = function(size)
{
    process.stdin.removeAllListeners('data').on('data', function(chunk)
    {
        readable.push(chunk);
    });
};

readable.on('data', function(chunk)
{
    if (pseudo.length == 0)
    {
        // TODO : méthode utilitaire pour formatter la string moisie
        pseudo = chunk.toString().replace(/\r|\n/g, "");
        console.log("Bonjour " + pseudo);
        connect();
    }
    else
    {
    console.log("3");
        if (chunk.toString().replace(/\r|\n/g, "") == "exit")
        {
        console.log("4");
            client.sendEndMessage({pseudo : pseudo, message : chunk});
        }
        else
        {
        console.log("5");
            client.sendMessage({pseudo : pseudo, message : chunk, isMessage : true});
        }
    }   
});

function connect()
{
    client.connect(port, host);

    client.on('connect', function()
    {
        client.sendMessage({pseudo : pseudo});

        client.on('message', function(message) {
            console.log(message);
        });
    });

    client.on('error', function()
    {
        console.log("Perte de connexion");
        connect();
    });

    client.on('end', function()
    {
        process.stdin.pause();
    });
};

1 个答案:

答案 0 :(得分:1)

I think you will find it is because of this line in server.js being in the wrong place:

sockets.push({socket : socket, pseudo : sender});

It should be done as part of the "connection" handler and not every time there is a message.

Edit:

I ran your code and from the json-socket example, I did not pass in a callback function to createServer, rather I left creating the handlers separately: (this seems to work!)

var net = require('net'), JsonSocket = require('json-socket');
var sockets = [];
var server = net.createServer();

server.on('connection', function(socket) { //This is a standard net.Socket
    socket = new JsonSocket(socket); //Now we've decorated the net.Socket to be a JsonSocket

    console.log('Connection');

    socket.on('message', function(message) {

        console.log("0");

        if (message.isMessage == null)
        {
            console.log("1");
            var sender = message.pseudo;
        sockets.push({socket : socket, pseudo : sender});
        console.log('Clients connected =', sockets.length());

            sockets.forEach(function(s)
            {
                s.socket.sendMessage(sender + " vient de se connecter");
            });

            console.log(sender + " vient de se connecter");
            console.log("Il y a " + sockets.length + " clients connectés");
        }
        else
        {
            console.log("2");
            var sender = message.pseudo;
            sockets.forEach(function(s)
            {
                if (s.pseudo.toString() != sender.toString())
                {   
                    console.log("3");
                    s.socket.sendMessage(sender + " : " + message.message);
                }
            });
        }
    });
});

server.on('error', function()
{
    socket.emit('end');
});

server.on('end', function()
{
    // TODO : fix this part
    //sockets.slice(sockets.indexOf(socket), 1);
    console.log("Il reste " + sockets.length + " clients connectés");
});


server.on('listening', function()
{
    console.log('Server launched');
});

server.listen(3000);