简体   繁体   中英

Sending data through node.js tcp socket from html page

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?

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM