Answer the question
In order to leave comments, you need to log in
How to create a Node.js server, [statefull, stateless, echo]?
Good afternoon.
There was a need to make a server, on node.js, which will recognize simple commands and respond to them.
You need to use the network module.
I see Node.js for the first time, to which they answered: "well, you make websites."
I tried various combinations from the tutorials. In order to force the server to respond at least to something. At the beginning, everything looked like this (in order to get at least some kind of response):
var http = require('http');
http.createServer(function(request, response) {
response.writeHead(200);
request.pipe(response);
}).listen(8080);
const net = require('net');
var server = net.createServer(function(socket) {
socket.end('goodbye\n');
}).on('error', function(err) {
throw err;
});
server.listen(function(){
address = server.address();
console.log('opened server on %j', address);
});
-->open (client request)
<--opened (server response)
-->add
<--added
-->process
<--processed
stateful & statelessserver?
Answer the question
In order to leave comments, you need to log in
This is roughly how it's done:
'use strict';
const net = require('net');
const server = net.createServer(socket => {
var data = '';
socket.on('data', d => {
data += d;
var p = data.indexOf('\n');
if(~p) {
let cmd = data.substr(0, p);
data = data.slice(p + 1);
onCommand(cmd.trim(), socket);
}
});
});
server.listen(() => {
var address = server.address();
console.log('opened server on', address);
});
function onCommand(cmd, socket) {
switch(cmd) {
case 'open':
socket.write('opened\n');
break;
case 'add':
socket.write('added\n');
break;
case 'process':
socket.write('processed\n');
break;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question