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

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 WorldnMy first node.js appnn -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.


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

链接地址: http://www.djcxy.com/p/52684.html

上一篇: 使用Node.js的Express 4.0最新教程?

下一篇: 如何在两个node.js实例之间进行通信,一个客户端一个服务器