alexg
alexg

Reputation: 922

Creating a server listening on a `net` stream and reply using Node.js

Can someone give me a working example on how to create a server listening on the stream and reply when there is a request coming through.

Here's what I have so far:

var port = 4567,
    net = require('net');

var sockets = [];

function receiveData(socket, data) {
    console.log(data);

    var dataToReplyWith = ' ... ';

    // ... HERE I need to reply somehow with something to the client that sent the initial data
}

function closeSocket(socket) {
    var i = sockets.indexOf(socket);
    if (i != -1) {
        sockets.splice(i, 1);
    }
}

var server = net.createServer(function (socket) {
    console.log('Connection ... ');
    sockets.push(socket);
    socket.setEncoding('utf8');
    socket.on('data', function(data) {
        receiveData(socket, data);
    })
    socket.on('end', function() {
        closeSocket(socket);
    });
}).listen(port);

Will the socket.write(dataToReplyWith); do it?

Upvotes: 1

Views: 548

Answers (1)

mscdex
mscdex

Reputation: 106736

Yes, you can just write to the socket whenever (as long as the socket is still writable of course). However the problem you may run into is that one data event may not imply a complete "request." Since TCP is just a stream, you can get any amount of data which may not align along your protocol message boundaries. So you could get half a "request" on one data event and then the other half on another, or the opposite: multiple "requests" in a single data event.

If this is your own custom client/server design and you do not already have some sort of protocol in place to determine "request"/"response" boundaries, you should incorporate that now.

Upvotes: 1

Related Questions