Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beginner Node.JS net.createServer example

I am an old PERL coder trying to learn node.JS programming. I have question about the code I am writing to create a socket connection between a server and a client app.

The code below works. But I do not know how to accept data sent from the client to the server.

Basically what I want to do is very simple. Client connects to a Server listening on a socket, sends some information, which the Server reads and then sends information back to the Client. The only part I am not understanding is how to get the Server side to read/accept/display the data string sent from the Client.

Can someone please point me in the right direction? Thank you for your help in advance.

(My apologies for being ignorant.)

Here is the server side code:

var net = require('net');
var server = net.createServer(function(socket) {
    // confirm socket connection from client
    console.log((new Date())+'A client connected to server...');
    socket.on('data', function(data) {
        var json = JSON.parse(data.toString());
        console.log(json)
    });
    // send info to client
    socket.write('Echo from server: NODE.JS Server \r\n');
    socket.pipe(socket);
    socket.end();
    console.log('The client has disconnected...\n');
}).listen(10337, '192.168.100.1');

Here is the client code:

var net = require('net');

var client = new net.Socket();
client.connect(10337, '192.168.100.1', function() {
console.log('Connected');  // acknowledge socket connection
client.write('Hello, server! Love, Client.'); // send info to Server
});

client.on('data', function(data) {
console.log('Received: ' + data); // display info received from server
client.destroy(); // kill client after server's response
});

client.on('close', function() {
console.log('Connection closed');
});

I get an error on the server when I do this where it says the string sent from the client is an invalid token. here is the error message.

undefined:1

Hello, server! Love, Client.
^
SyntaxError: Unexpected token H
at Object.parse (native)
at Socket.<anonymous> (/root/nodejs/server-example.js:7:19)
at Socket.emit (events.js:117:20)
at Socket.<anonymous> (_stream_readable.js:765:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:427:10)
at emitReadable (_stream_readable.js:423:5)
at readableAddChunk (_stream_readable.js:166:9)
at Socket.Readable.push (_stream_readable.js:128:10)
at TCP.onread (net.js:529:21)
like image 588
Net Admin Avatar asked Sep 27 '22 18:09

Net Admin


1 Answers

I was being stupid. I found the answer I was looking for. And it was very simple.

Here is what I should have written in place of the JSON statements

    socket.on('data', function(data) {
            var string = (data.toString());
            console.log(string)
    });
like image 168
Net Admin Avatar answered Oct 07 '22 16:10

Net Admin