如何解析通过管道接收的消息

How to parse messages received through pipe

本文关键字:消息 管道 何解析      更新时间:2023-10-16

我创建了我的管道服务器,它创建了一个实例管道通过使用函数 ConnectNamedPipe。之后,我从管道中读取并将数据保存到缓冲区中。我还没有创建我的客户端,但我必须做一些操作。

我的客户必须写入管道 2 件事:1 - 服务器将执行的操作 - 减法,乘法,加法,除法(我正在尝试实现一种计算器)服务器将计算的 2 - 2 个数字

我的服务器必须从管道中读取这些操作和 2 个数字并将结果打印在屏幕上。

所以,我的问题是,我如何解析客户端编写的那 2 个操作?

我的服务器工作正常,但我在解析时遇到问题。

#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
    HANDLE createPipe;
    BOOL Connect;
    BOOL Read;
    int buffer[100];
    DWORD numBytesRead;
    //Create Pipe
    createPipe = CreateNamedPipe(
        L"\\.\pipe\StackOverflow",
        PIPE_ACCESS_DUPLEX,
        PIPE_TYPE_MESSAGE,
        PIPE_UNLIMITED_INSTANCES,
        1024,
        1024,
        NMPWAIT_USE_DEFAULT_WAIT,
        NULL);
    //Check for failure
    if(createPipe == INVALID_HANDLE_VALUE){
        cout<<"Failed to create a pipe! "<<endl;
    }
    //Create instance of the pipe
    Connect = ConnectNamedPipe(
        createPipe,
        NULL);
    //Check for failure
    if(!(Connect)){
        cout<<"Failed to connect to the pipe"<<endl;
        CloseHandle(createPipe);
    }
    //Read bytes from the buffer
    Read = ReadFile(
            createPipe, 
            buffer,
            99 * sizeof(buffer),
            &numBytesRead,
            NULL);
    //check for failure
    if(!(Read)){
        cout<<"Failed to read from the pipe"<<endl;
        CloseHandle(createPipe);
    }
    return 0;
}

感谢

您应该研究序列化 - 应该封装如何编码和解码管道数据。你有一个计算对象,它有两个操作数元素(数字)和一个操作(也许是枚举?) - 那么问题就变成了如何序列化(发送)和反序列化(接收)该对象,独立于管道 I/O。

查看 Boost.Serialization 了解概念 - boost.org/doc/libs/1_49_0/libs/serialization/doc/index.html