通过命名管道

时间:2018-02-10 08:20:28

标签: c++ named-pipes

我正在尝试通过命名管道传递包含字符串的结构,这是我到目前为止使用的内容:

** ClientMessage:*

    ClientMessage(const long id, const int action, const std::wstring name)
    : mId(id), mAction(action), mName(name) {};
ClientMessage(std::wstringstream& inputStream) {
    Deserialize(inputStream);
}
~ClientMessage() {};

std::wstringstream& ClientMessage::Serialize(std::wstringstream &out) const
{
    out << mId
        << L'|'
        << mAction
        << L'|'
        << mName.size()
        << L'|'
        << mName.c_str();
    return out;
}

std::wstringstream& ClientMessage::Deserialize(std::wstringstream &in)
{
    if (in) {
        int len = 0;
        wchar_t separator;
        in >> mId;
        in >> separator;
        in >> mAction;
        in >> separator;
        in >> len;
        if (in && len) {
            mName.resize(len);
            in.read(&mName[0], len);
        }
    }
    return in;
}

服务器

ClientMessage message(1, 123, L"TestName");

DWORD bytesWritten = 0;
std::wstringstream buffer;
message.Serialize(buffer);
int size = buffer.str().size() * sizeof(WCHAR);
BOOL result = ::WriteFile(this->m_CommPipe, buffer.str().c_str(), size, &bytesWritten, nullptr);

客户端

DWORD dwBytesRead = 0;
int multiplier = 1;
std::vector<WCHAR> buffer;
while(true) {
    DWORD bytesToRead = 1024 * multiplier;
    result = ::ReadFile(pipe, &buffer[0], bytesToRead, &dwBytesRead, nullptr);
    if (ERROR_MORE_DATA == ::GetLastError()) {
        multiplier*=2;
        continue;
    } else if (!result) {
        break;
    }
    std::wstringstream inputStream;
    inputStream.write(&buffer[0], buffer.size());
    ClientMessage message(inputStream);
}

在我尝试反序列化数据之前,通过检查inputStream的内容,我可以看到字符串不正确。

0 个答案:

没有答案