简体   繁体   中英

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. 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.

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 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
  • Broadcasted message will be received by only one server at a time, out of multiple servers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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