目的:nodejs和php通讯
实现:通过socket协议tcp使nodejs和php相互通讯! 首先 nodejs建立http服务器,然后建立tcp监听(用作client),然后php建立tcp服务器
源代码:
var http = require('http');
http.createServer(function (req, res) {
// res.writeHead(200, {'Content-Type': 'text/plain'});
// res.end('Hello World\n');
if( req.url !=''){
var net = require('net');
var client = net.connect({port: 8124},
function() { //'connect' 监听器
console.log('client connected');
client.write(req.url+'world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(data.toString()+'\n');
});
client.on('end', function() {
console.log('客户端断开连接');
});
}
}).listen(133