Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to communicate between two node.js instances, one client one server

Tags:

node.js

I am a beginner in node.js (infact started just today). One of the basic concepts is not clear to me, which I am asking here & couldn't find on SO.

Reading some tutorials on the web I wrote a client side & a server side code:

Server side (say server.js):

var http = require('http'); //require the 'http' module

//create a server
http.createServer(function (request, response) {
  //function called when request is received
  response.writeHead(200, {'Content-Type': 'text/plain'});
  //send this response
  response.end('Hello World\nMy first node.js app\n\n -Gopi Ramena');
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

Client side (say client.js):

var http=require('http');

//make the request object
var request=http.request({
  'host': 'localhost',
  'port': 80,
  'path': '/',
  'method': 'GET'
});

//assign callbacks
request.on('response', function(response) {
   console.log('Response status code:'+response.statusCode);

   response.on('data', function(data) {
     console.log('Body: '+data);
   });
});

Now, to run the server, I type node server.js in the terminal or cmd prompt. & it runs successfully logs the message in the console & also outputs the response when I browse to 127.0.0.1:1337.

But, how to I run client.js? I could not understand how to run the client side code.

like image 981
gopi1410 Avatar asked Jun 18 '12 18:06

gopi1410


People also ask

How do I connect two node JS servers?

Server A (Client): log('1'); // Connect to server var io = require('socket. io-client'); var socket = io. connect('http://localhost:8080', {reconnect: true}); console.

Can I use node on the client side?

Other reasons why we cannot use node modules at the client side is that the node uses the CommonJS module system while the browser uses standard ES Modules which has different syntax.

How many connections NodeJS can handle?

To address these issues, Node. JS uses a single thread with an event-loop. In this way, Node can handle 1000s of concurrent connections without any of the traditional detriments associated with threads. There is essentially no memory overhead per-connection, and there is no context switching.


1 Answers

Short answer: you can use the command

node client.js

to run your "client side" code, it will send one http request

Regarding to what's server side and what's client side, it's really depends on the context.

Although in most cases, client side means the code running on your browser or your mobile phone app, server side means the "server" or "back end" your browser or your mobile phone is talking to.

In your case, I think it's more like one "server" talks to another "server", and they are both on the back end, since that's what node.js is designed for

like image 144
xvatar Avatar answered Oct 04 '22 14:10

xvatar