我是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