0
这里是东西:节点JS Express和简单的socket服务器
我想创建一个简单的API服务器,从用户请求被解析并翻译到发送到socket服务器简单的套接字消息。
下面是代码
的Express服务器:
var express = require('express');
var app = express(),
handler = require('./lib/urlparser.js');
app.get('/', function(req, res){
var body = 'Hello World';
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', body.length);
res.end(body);
});
app.get('/:command/:mode/:addr/:value', handler.handleRequest);
app.listen(80);
console.log('Listening on port 80...');
而且这个handleRequest模块
exports.handleRequest = function(req, res) {
var net = require('net');
var HOST = '192.168.1.254';
var PORT = 8888;
var client = new net.Socket();
/* translate the url params and save it to var request and send it */
/* The code goes here */
client.connect(PORT, HOST, function() {
//console.log('Connected To: ' + HOST + ':' + PORT);
client.setEncoding('utf-8');
client.write(request);
//console.log('Message Sent');
});
client.on('data', function(val) {
//console.log('The Data: ' + val);
res.send([{addr:'test'}, {value: val}]);
client.destroy();
});
client.on('close', function() {
//console.log('Connection closed');
});
};
此代码的工作,我只需要知道是正确的或者是还有什么方式来包含网络模块,并在主js文件中声明套接字服务器的ip和端口(在模块外部)?
任何帮助,将不胜感激。