我正在尝试开发一种类似于Client方法的请求响应系统,在客户机中从服务器请求它的数据。服务器的响应以二进制格式从文件中读取并发送到相应的客户端,文件大小几乎是由120行组成的35 KB。
该文件的原型如下:
line-1: abcdefghijklmnopqrstuvwxyz
line-2: abcdefghijklmnopqrstuvwxyz
line-3: abcdefghijklmnopqrstuvwxyz
line-4: abcdefghijklmnopqrstuvwxyz
line-5: (FOR CLIENT-235)abcdefghijklmnopqrstuvwxyz
line-6: abcdefghijklmnopqrstuvwxyz
line-7: (FOR CLIENT-124)abcdefghijklmnopqrstuvwxyz
line-8: abcdefghijklmnopqrstuvwxyz
.
.
.
line-119: (FOR CLIENT-180)abcdefghijklmnopqrstuvwxyz
line-120: abcdefghijklmnopqrstuvwxyz前四行为服务器,下四行为客户端。从第五行开始,特定客户端所需的数据将是两行,即如果请求来自CLIENT-235,服务器必须保存第5行和第6行数据,以便在容器中进行未来事务并发送给它。如果同一个客户再次请求,发送第5行和第6行,而不读取整个文件。其他客户也有类似的做法。
维护一个Index文件会更容易吗?对于特定的行和信息,我需要一个Map?
我想知道使用Vector或简单structures实现这一目标的最佳方法(至少更好)是什么?因为文件中的行数可能会增加,所以我需要某种动态数组吗?
发布于 2013-09-26 13:35:16
一种方法是使用STL的地图来实现你想要的。因为每个客户端的响应都是两行字符串,所以可以创建一个包含两个变量的结构来存储它。然后,您可以将结构插入到映射中,并以"CLIENT-X“作为索引元素。最后,使用索引检索客户端的数据。以下是一个例子:
#include <sstream>
#include <fstream>
#include <map>
#include <string>
using namespace std;
struct data
{
string firstLine, secondLine;
data(){ }
};
int main()
{
ifstream file("input.txt");
std::map<string,data> mymap;
stringstream ss;
string index;
data buffer;
int client = 1;
if(file.is_open())
{
string server[4];
for(int i = 0; i < 4; i++) // read the first 4 lines for the server
getline(file, server[i]);
while(getline(file, buffer.firstLine))
{
getline(file, buffer.secondLine);
// define the index value for retrieval
ss.str("");
ss << "CLIENT-" << client;
// insert the client's data into the map
mymap.insert(pair<string,data>(ss.str(), buffer));
client++;
}
// retrieve the client's data
buffer = mymap["CLIENT-1"]; // example on how to access
// here you can do what you want, like sending to the client
//
file.close();
}
return 0;
} https://stackoverflow.com/questions/19028410
复制相似问题