管道同步通信

管道通信,一对一通信例子。

服务端:

 1 #include <stdio.h>
 2 #include <Windows.h>
 3 
 4 int main(void)
 5 {
 6     HANDLE hPipe = NULL;
 7     char buf[255] = { 0 };
 8     DWORD dwLen = 0;
 9 
10     // 创建命名管道
11     hPipe = CreateNamedPipe("\\.\Pipe\biaoge",  // 管道名字
12         PIPE_ACCESS_DUPLEX,                            // 可读写
13         PIPE_TYPE_MESSAGE | PIPE_WAIT,                // 消息类型 阻塞模式
14         PIPE_UNLIMITED_INSTANCES,                    // 最大实例 该常量代表255
15         NULL,                                        // 默认输出缓存大小
16         NULL,                                        // 默认输入缓存大小
17         NULL,                                        // 默认客户端超时
18         NULL                                        // 默认安全属性
19         );
20     if (hPipe == INVALID_HANDLE_VALUE)
21     {
22         printf("CreateNamedPipe failed:%d.
", GetLastError());
23         return 0;
24     }
25 
26     printf("Wait client connect...
");
27     // 等待客户端连接
28     if (ConnectNamedPipe(hPipe, NULL) == 0)
29     {
30         printf("ConnectNamedPipe failed:%d.
", GetLastError());
31         return 0;
32     }
33     printf("Client in
");
34     // 客户端进入,读取客户端发送的数据
35     if (ReadFile(hPipe, buf, sizeof(buf), &dwLen, NULL))
36     {
37         printf("Recv:[%s]
", buf);
38         // 向客户端发送数据
39         if (WriteFile(hPipe, "Hello Client!", 15, &dwLen, NULL))
40         {
41             printf("Send client data success!
");
42         }
43         else
44         {
45             printf("Send client data failed!
");
46         }
47     }
48     // 关闭管道
49     CloseHandle(hPipe);
50     system("pause");
51     return 0;
52 }

客户端:

 1 #include <stdio.h>
 2 #include <Windows.h>
 3 
 4 int main(void)
 5 {
 6     HANDLE hPipe = NULL;
 7     DWORD dwLen = 0;
 8     char str[255] = "Hello Biaoge,Testing Pipe!";
 9 
10     // 连接管道
11     hPipe = CreateFile("\\.\Pipe\biaoge", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
12     if (hPipe == INVALID_HANDLE_VALUE)
13     {
14         printf("Connect server pipe failed:%d.
", GetLastError());
15         return 0;
16     }
17     printf("Connect server success!
");
18     // 连接成功,向服务端发送一条数据
19     if (WriteFile(hPipe,str , lstrlen(str)+1, &dwLen, NULL))
20     {
21         printf("Send data success!
");
22     }
23     else
24     {
25         printf("Send data failed:%d.
", GetLastError());
26         return 0;
27     }
28     // 接收服务端数据
29     if (ReadFile(hPipe, str, sizeof(str), &dwLen, NULL))
30     {
31         printf("Recv server data:[%s]
", str);
32     }
33     else
34     {
35         printf("Recv server data failed!
");
36     }
37     // 关闭管道
38     CloseHandle(hPipe);
39     system("pause");
40     return 0;
41 }

效果图

原文地址:https://www.cnblogs.com/biaoge140/p/9538425.html