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

gop*_*410 19 node.js

我是node.js的初学者(事实上刚刚开始).其中一个基本概念对我来说并不清楚,我在这里要求并且在SO上找不到.

在网上阅读一些教程,我写了一个客户端和服务器端代码:

服务器端(比如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/');
Run Code Online (Sandbox Code Playgroud)

客户端(比如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);
   });
});
Run Code Online (Sandbox Code Playgroud)

现在,要运行服务器,我键入node server.js终端或cmd提示符.&它成功运行在控制台中记录消息,并在浏览到127.0.0.1:1337时输出响应.

但是,如何运行client.js?我无法理解如何运行客户端代码.

xva*_*tar 10

简答:您可以使用该命令

node client.js
Run Code Online (Sandbox Code Playgroud)

要运行"客户端"代码,它将发送一个http请求

关于什么server side和什么client side,它实际上取决于背景.

虽然在大多数情况下,client side意味着您的浏览器或手机应用程序上运行的代码,server side意味着您的浏览器或手机正在与之通信的"服务器"或"后端".

在你的情况下,我认为它更像是一个"服务器"与另一个"服务器"对话,并且它们都在后端,因为这就是node.js的设计目的

  • @ gopi1410你需要在最后添加`request.end();` (3认同)