我是node.js的初学者(实际上是在今天开始的)。其中一个基本概念对我来说是不清楚的,我在这里问的是&在SO上找不到。如何在两个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/');
客户端( 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);
});
});
现在,要运行服务器,我在终端或cmd提示符下输入node server.js
。 &它成功运行在控制台中记录消息&也会在浏览到127.0.0.1:1337时输出响应。
但是,我该如何运行client.js?我无法理解如何运行客户端代码。
节点是服务器端不客户端。看看这个。 http://stackoverflow.com/questions/5168451/javascript-require-on-client-side –
不知道你在哪里找到client.js或你期望它做什么,但这不是你可以放在浏览器中的东西。如果客户端,你的意思是另一个Node.js应用程序。我认为你找到的教程指导你如何编写一个服务器来访问其他服务器上的HTTP资源。 – Brad
你从哪里找到'client.js'?你自己写了吗?你想用这个来达到什么目的? – jsalonen