Saturday, 20 May 2017

A bridge to access node tcp server from ajax

I am learning node.js (dummy/newbie level). I made TCP server-client by guidance of tutorials. It runs well. I also made node http server and it also runs well.

I want to access TCP server from browser. No direct method, so I try this.

Purpose: an http bridge to access TCP server from XMLHttpRequest.

  1. Create TCP server
  2. Create HTTP server
  3. Combine HTTP server and TCP client
  4. Assign request from HTTP server to TCP client
  5. TCP client send to TCP server

Here is the "bridge", which I combine from two tutorials.

var http = require("http");
var net = require('net');
var port = 4001;
var quitting = false;
var conn;
var retryTimeout = 3000; // 3 seconds
var retriedTimes = 0;
var maxRetries = 10;
var body = '';

(function connect() {
  function reconnect() {
    if (retriedTimes >= maxRetries) {
      throw new Error('Max retries have been exceeded, I give up.');
    }
    retriedTimes += 1;
    setTimeout(connect, retryTimeout);
  }
  conn = net.createConnection(port);
  conn.on('connect', function() {
    retriedTimes = 0;
    console.log('connected to server');
  });
  conn.on('error', function(err) {
    console.log('Error in connection:', err);
  });
  conn.on('close', function() {
    if (! quitting) {
      console.log('connection got closed, will try to reconnect');
      reconnect();
    }
  });

}());

var httpserver = http.createServer(function(req, res) {
  if(req.method=='POST'){  
    req.on('data', function(data){
      body += data;
    });
    req.on('end', function(){
      console.log(body);
      conn.write(body); // => feed TCP server
      conn.pipe(res); // => feed back from TCP server send to http server response 
      res.writeHead(200, { "Content-Type": "text/plain", "Access-Control-    Allow-Origin":"*"});

      res.end();
    });
  }
}).listen(8000);

console.log(8000);

This script results:

  1. TCP server connected to http server and counted it as its client.
  2. Http server failed to send feed to TCP client.
  3. HTTP server do not get TCP feedback (response).


via J Does

No comments:

Post a Comment