通过套接字连接使用 node.js 查询 sqlite3 数据库时,我遇到以下 2 个问题:
使用 node.js http 客户端我请求 node.js http 服务器,结果的顺序混淆了
有时我的套接字挂断,它无法重现
这是服务器代码:
var http = require('http');
var url = require('url');
var sqlite3 = require('sqlite3').verbose();
var counter = 0;
//create sqlite database for testing
var db = new sqlite3.Database("db.sqlite3");
db.serialize(function() {
db.run("DROP TABLE IF EXISTS test");
db.run("CREATE TABLE IF NOT EXISTS test (ID INTEGER)");
var stmt = db.prepare("INSERT INTO test VALUES (?)");
for (var i = 1; i <= 10; i++) {
stmt.run(i);
}
stmt.finalize();
});
db.close();
//run server
http.createServer(function (req, res) {
var queryData = url.parse(req.url, true).query;
res.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"});//, "connection": "keep-alive"
var db = new sqlite3.Database(new Buffer(queryData.SQLServerAddress, "base64").toString('utf8'));
db.serialize(function() {
db.each(new Buffer(queryData.SQLStatement, "base64").toString('utf8'), function(err, row) {
counter++;
console.log(counter + " / " + JSON.stringify(row));
res.end(JSON.stringify(row).toString());
});
});
db.close();
counter = 0;
}).listen(1337, '127.0.0.1');
console.log('Server running...');
这是客户端代码:
var http = require('http');
for(i=1;i<=10;i++){
var SQLServerAddress = new Buffer("db.sqlite3").toString('base64');
var SQLStatement = new Buffer("SELECT * FROM test WHERE ID=" + i).toString('base64');
var options = {
host: "127.0.0.1",
port: 1337,
path: "/?SQLServerAddress=" + SQLServerAddress + "&SQLStatement=" + SQLStatement
};
callback = function(response){
var str = "";
response.on("data", function (chunk){
str += chunk;
});
response.on("end", function (){
console.log(str);
});
}
http.request(options, callback).end();
}
我将请求重复 10 次作为“压力测试”,有点……
所以我在控制台中收到的是例如
服务器端控制台:
1 / {"ID":1}
2 / {"ID":2}
3 / {"ID":5}
4 / {"ID":4}
1 / {"ID":3}
2 / {"ID":6}
1 / {"ID":7}
2 / {"ID":9}
3 / {"ID":10}
4 / undefined
和客户端控制台:
{"ID":1}
{"ID":2}
{"ID":5}
{"ID":4}
{"ID":3}
{"ID":6}
{"ID":7}
{"ID":9}
{"ID":10}
events.js:68
throw arguments[1]; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1263:15)
at Socket.socketCloseListener (http.js:1314:23)
at Socket.EventEmitter.emit (events.js:123:20)
at Socket._destroy.destroyed (net.js:357:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
我的问题是:
- 如何以正确的顺序保持结果?
- 我该怎么做才能防止套接字挂断?
提前致谢!