Windows 2012 server not executing socket.on

时间:2015-07-28 17:13:12

标签: node.js sockets

I am trying to learn to use NodeJS and JavaScript to replace at least some of my Perl code.

I need to create a socket and have a server/listener accept data sent from a client.

The problem I am having is that under Windows 2012 server, the listener code below just completely ignores the socket.on command, but it works fine under CentOS.

Does anyone have any suggestions as to what I am missing?

var net = require('net');
var fs  = require('fs');

var server = net.createServer(function(socket) {

    console.log('At : ' + (new Date()) + '\nA client connected to server...');
    console.log('IP addr : ' + socket.remoteAddress);

    // Process data sent from client
    socket.on('data', function(data) {

        console.log('Reached socket.on function.\n');

        // Following command reads the data stream from client
        var string = ('IP addr : '+ socket.remoteAddress + ' sent on ' + (new Date()) + ' : ' + data.toString()+'\n');
        console.log(string);

        // Following command writes the data stream to a file
        fs.appendFile('client-data', string, function(err) {
            if (err) {
                return console.log(err);
            }
            console.log('Data saved from client...');
        });
    });

    // This section sends data back to client, close socket, and 
    // resets to accept new socket connection
    socket.write('\n<svrdata>\nData received by : HS-AD02 \r\n</svrdata>');
    socket.pipe(socket);
    socket.end();

    console.log('The client has disconnected...\n');

}).listen(10337, 'hs-ad02');

1 个答案:

答案 0 :(得分:0)

在上面的代码中,问题有一个非常简单的解决方案。 在Windows下的两行     socket.pipe(插座);     socket.end();
导致套接字在收到客户端数据之前关闭。

删除这两行并且它可以正常工作。