NodeJS Net.createServer

时间:2018-05-14 12:47:05

标签: node.js

嘿呃我遇到了问题,我认为这可能与net.createserver有关。

问题是,每当第一个客户端加入另一个第二个客户端加入后,第一个客户端可以控制第二个客户端,然后第一个客户端断开连接,因为套接字(结束)事件被触发。它与套接字有什么关系,或者服务器无法处理两个连接?请帮忙

代码:

    handleGame: function() {
    console.log(log.success('The source is starting!'));
    var server = net.createServer(function(socket) {
        console.log('A client has connected' + "\r\n");
        socket.setEncoding('utf8')
        global.clientObjz = new client(socket);
        game.addClient(clientObjz);
        socket.on('data', function(data) {
            data = data.toString().split('\0')[0];
            console.log('Incoming data: ' + data + "\r\n")
            if (data == "<msg t='sys'><body action='verChk' r='0'><ver v='153' /></body></msg>" | data == "<msg t='sys'><body action='rndK' r='-1'></body></msg>" | data.startsWith("<msg t='sys'><body action='login' r='0'>")) {
                parseXml(data, function(err, result) {
                    var type = result.msg['$'].t,
                        action = result.msg.body[0]['$'].action;

                    var method = Game.xmlHandlers[type][action];

                    if (typeof Game[method] == 'function') {
                        Game[method](data, client);
                    }
                });
            }
            var dataType = data.charAt(0);
            if (dataType == '%') {
                game.handleraw(data, clientObjz);
            }
        });
        socket.on('end', function() {
            game.removeClient(socket);
            console.log('A client has disconnected');
        });
        socket.on('error', function(err) {

         console.log(err);
        });
    });

    server.listen(Game1, "localhost", function() {
        console.log('Server is listening on port 6113');
    });

}

//this code is another file as i am calling it by game.clients.push
 addClient: function(client) {
    if (client) {
        self.clients.push(client);
    }
}

是的,它是一个clubpenguin模拟器

完整代码:https://github.com/dev3211/bingojs

1 个答案:

答案 0 :(得分:0)

如果仅使用NodeJS net.createServer执行此操作,则需要实现套接字通道。如果你想要它简单,你可以使用express.js寻找一些东西,如下所示:https://medium.com/factory-mind/websocket-node-js-express-step-by-step-using-typescript-725114ad5fe4