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

我是node.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.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); }); }); 

现在 ,要运行服务器,我在terminal或cmd提示符下inputnode server.js 。 &它成功运行在控制台中logging消息,并在浏览到127.0.0.1:1337时输出响应。

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

简短的回答:你可以使用这个命令

 node client.js 

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

关于server sideclient side是什么,真的取决于上下文。

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

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