简体   繁体   English

是否可以在服务器和多个客户端之间的命名管道中广播消息?

[英]Is it possible to broadcast messages in named pipe between a server and multiple clients?

I am new to pipes and interprocess communication in windows.我是 Windows 中管道和进程间通信的新手。 I want to use named pipe to communicate between processes.我想使用命名管道在进程之间进行通信。 But in my case I should send message to multiple clients, so I want to check is it possible to send broadcast messages in named pipe communication.但在我的情况下,我应该向多个客户端发送消息,所以我想检查是否可以在命名管道通信中发送广播消息。 Thank you in advance.先感谢您。

This namedpipe client will broadcast 40 messages one message per second which will be received one of the multiple servers which are connected to same pipe.这个命名管道客户端将每秒广播 40 条消息,一条消息将被连接到同一管道的多个服务器之一接收。

NamedPipe Client命名管道客户端

std::wcout << L"I am broadcasting messages!\n"; 
TCHAR                       chReadBuf[_MAX_PATH] = { 0 };
LPTSTR                      lpszWrite= TEXT("Default message from client");
DWORD                       cbRead = 0;
TCHAR                       szTempFolderPath[_MAX_PATH] = { 0 };
TCHAR                       aTempFileName[_MAX_PATH] = { 0 };

for (int i=0; i<40;i++)
{
    std::wcout<< lpszWrite << std::endl;

    CallNamedPipe(L"\\\\.\\pipe\\my_pipe", lpszWrite, (lstrlen(lpszWrite) + 1) * sizeof(TCHAR), chReadBuf, (_MAX_PATH * _MAX_PATH) * sizeof(TCHAR), &cbRead, NMPWAIT_WAIT_FOREVER);
Sleep(1000);
}

Create multiple namedpipe servers each server is using same pipe, which is used by namedpipe client to broadcast message.创建多个 namedpipe 服务器,每个服务器都使用相同的管道,namedpipe 客户端使用它来广播消息。

NamedPipe Server命名管道服务器

HANDLE      m_hPipe = nullptr;
m_hPipe = CreateNamedPipe(L"\\\\.\\pipe\\my_pipe", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, MAX_PATH * MAX_PATH, MAX_PATH * MAX_PATH, 100000, NULL);
            
do {
        HRESULT             hr = S_OK;
        TCHAR       chReadBuf[MAX_PATH * MAX_PATH];
        BOOL        fSuccess = FALSE;
        DWORD       cbRead;

        ConnectNamedPipe(m_hPipe, NULL);
    
        fSuccess = ReadFile(
            m_hPipe,      // pipe handle 
            chReadBuf,  // buffer to receive reply 
            (MAX_PATH * MAX_PATH) * sizeof(TCHAR),  // size of buffer 
            &cbRead,  // number of bytes read 
            NULL);    // not overlapped 

        chReadBuf[cbRead] = '\0';
        std::wcout <<L"Received by Server 1" << chReadBuf << std::endl;

        DisconnectPipe();

    } while (1);
  • Make note that all your servers should use same pipename as given in above code \\\\.\\pipe\\my_pipe请注意,您的所有服务器都应使用与上述代码 \\\\.\\pipe\\my_pipe 中给出的相同的管道名称
  • Broadcasted message will be received by only one server at a time, out of multiple servers.广播消息一次只能由一台服务器接收,而不是多台服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM