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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11088720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:53:18  来源:igfitidea点击:

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

node.js

提问by gopi1410

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.

我是 node.js 的初学者(实际上是从今天开始的)。我不清楚其中一个基本概念,我在这里问并且在 SO 上找不到。

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

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

Server side (say server.js):

服务器端(比如 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):

客户端(比如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.jsin 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.

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

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

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

采纳答案by xvatar

Short answer: you can use the command

简短回答:您可以使用命令

node client.js

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

运行您的“客户端”代码,它将发送一个 http 请求

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

关于 what'sserver side和 what's client side,这实际上取决于上下文。

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

尽管在大多数情况下,client side意味着在您的浏览器或您的手机应用程序上运行的代码,server side意味着您的浏览器或您的手机正在与之通话的“服务器”或“后端”。

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

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