1

我正在尝试开发一个类似于客户端-服务器方法的请求-响应系统,其中客户端从服务器请求其数据。来自服务器的响应从二进制文件中读取并发送到相应的客户端,文件大小几乎35 KB由 120 行组成。

该文件的原型如下:

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

前四行用于服务器,接下来的 116 行用于客户端。从 5 号开始,特定客户端所需的数据将是两行,即如果请求来自 CLIENT-235,则服务器必须将第 5 行和第 6 行数据保存在容器中以供将来的事务处理并发送给它。如果同一个客户端再次请求,发送第 5 行和第 6 行而不读取整个文件。其他客户的类似方法。

维护一个Index文件会更容易,它将为特定的行和信息建立索引 - 我需要一个Map吗?

我想知道使用Vector或简单实现此目的(至少更好的方法)的最佳方法是什么structures?因为文件中的行数可能会增加,所以我需要排序动态数组吗?

4

1 回答 1

0

一种方法是使用 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;
}   
于 2013-09-26T13:35:16.547 回答