首先通过nodejs和mongodb建立后端服务器
一、在windows平台下启动mongodb服务器
1、进入mongodb的安装目录,并进去bin目录启动mongod
2、在d盘建立mongodbdata文件夹作为数据存储目录
mongod.exe --dbpath d:mongodbdata
二、建立js文件,并通过nodejs启动
1、当向服务器发送01指令时,服务器将从mongodb 读取数据,并返回
var HOST = "localhost"; var PORT = 6969; var dgram = require('dgram'); var server_udp = dgram.createSocket('udp4'); var mongo=require("mongodb"); var DB_PORT=27017; var server_database=new mongo.Server(HOST,DB_PORT,{auto_reconnect:true}); var db=new mongo.Db("test",server_database,{safe:true}); db.open(function (err,db) {//连接数据库 if(err) { console.log("error"); throw err; } else{ db.collection("student", function (err,collection) { collection.insert({ name:"jinjian",score:"100"}, function (err,docs) { console.log(docs); db.close(false); }); }); } }); server_udp.on('listening',function(){ var address = server_udp.address(); console.log("server listening " + address.address + " : "+ address.port); console.log(" "); }); server_udp.on('message',function(message,remote){ console.log(""+message); switch( ""+message) { case ("01"): { console.log("receive 01"); db.open(function (err,db) { db.collection("student", function (err,collection) { if(err) throw err; else{ collection.find({}).toArray(function(err,docs){ if(err) throw err; else{ var str = JSON.stringify(docs); server_udp.send(str,0,str.length,6967,remote.address); console.log(str); db.close(false); } }); } }); }); break; } case ("02"): { console.log("receive 02"); break; } case ("03"): { console.log("receive 03"); break; } } console.log(remote.address +":" + message ); console.log(" "); }); server_udp.bind(PORT,HOST);
三、编写MFC界面
1、MFC接受到数据后解析代码如下(程序使用了jsoncpp-json数据解析库)
Json::Reader reader; Json::Value json_object; int len = strlen((char *)lParam); char* temp = new char [len]; memcpy(temp,(char *)lParam,len); if (!reader.parse(temp, json_object)) return 0; int size = json_object.size(); const Json::Value arrayObj = json_object; for (int i=0; i<arrayObj.size(); i++){ string id = arrayObj[arrayObj.size()-1-i]["number"].asString(); string name= arrayObj[arrayObj.size()-1-i]["name"].asString(); string score = arrayObj[arrayObj.size()-1-i]["score"].asString(); int n = m_list.InsertItem(0,id.c_str()); m_list.SetItemText(n,1,name.c_str()); m_list.SetItemText(n,2,score.c_str()); //fprintf(pfOutput, "%s ",id.c_str()); //fprintf(pfOutput, "%s ",firstname.c_str()); //fprintf(pfOutput, "%s ",username.c_str()); }
四、测试读取数据库,MFC向数据库发送“01”指令,并将返回的数据显示在列表中
1、向mongodb插入数据。进入mongodb程序的bin目录
D:Mongodbin>mongo
>use test
db.student.insert({"01":"x1","02","x2",.....});
2 MFC读取效果如下