0

Hy, I'm asking because I want to clear my mind about net sockets in Node.js:

I have an easy server that replicates the data received. It looks like this:

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 1337;

net.createServer(function(sock) {

    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

    sock.on('data', function(data) {

        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        sock.write('You told me: ' + data);

    });

    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

So, if I want to make a really easy html page like this:

<input type="text" name="data" value="" />
<input type="button" value="Send data" onclick="send()" />
<div id="result"></div>

Now I will click on the button and the page sends data to the server, and write the answer into the "result" div. What i need to write or use in the function "send()" (just in order to send the data and receive the answer)? I searched for things like this a lot, but wasn't lucky... I need to add an http server to the server file maybe?

1 Answer 1

1

I recommend you use SockJS module in server and client side. Look this example for client:

 var sock = new SockJS('YOUR_SOCKJS_URL');
 sock.onopen = function() {
     console.log('open');
 };
 sock.onmessage = function(e) {
     console.log('message', e.data);
 };
 sock.onclose = function() {
     console.log('close');
 };

 function send(){   // this for onclick="send()"
     sock.send();
 }  

For server use Sockjs module. example:

var http = require('http');
var sockjs = require('sockjs');

var echo = sockjs.createServer({ sockjs_url: 'http://cdn.jsdelivr.net/sockjs/0.3.4/sockjs.min.js' });
echo.on('connection', function(conn) {
    conn.on('data', function(message) {
        conn.write(message);
    });
    conn.on('close', function() {});
});

var server = http.createServer();
echo.installHandlers(server, {prefix:'/echo'});
server.listen(9999, '0.0.0.0');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks very much!!!! It works perfectly! For everyone else in the client you must add a reference to the sockjs.min.js file that you can find on Internet. The file Can be opened with every browser just clicking on it, whitout typing "localhost" on the URL bar. Thank you very much for the answer, it really helped!
I glad help you) Confirm answer pls

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.