pipe server client通信

这是一个关于在Windows环境下,使用C++实现管道通信的示例。代码创建了两个线程,一个用于Server的发送和接收,另一个用于Client的发送和接收。Server通过CreateNamedPipe创建管道,并等待Client连接。Client使用WaitNamedPipe等待管道建立,然后创建文件句柄进行通信。通信过程中,数据在Server和Client间双向传递。
摘要由CSDN通过智能技术生成

工程环境:vs2017

字符集为unicode, 所有用wchar_t;如果为多字符集,则用char. Server与Client的管道名称需一致。

工程中加入InitializeCriticalSection(cs);  的话,出现问题,所以暂时没有使用。

 

1.  // pipeServer.cpp: 定义控制台应用程序的入口点。  

2.  //  

3.    

4.  #include "stdafx.h"  

5.  #include <stdio.h>  

6.  #include <tchar.h>  

7.  #include <windows.h>  

8.  #include <process.h>  

9.  #include <stdlib.h>  

10. #include <conio.h>    

11.   

12. const wchar_t strPipeSend[30] = L"\\\\.\\pipe\\Pipe_demo_send";  

13. const wchar_t strPipeGet[30] = L"\\\\.\\pipe\\Pipe_demo_get";  

14.   

15.   

16. HANDLE get, mSend, mutex;  

17. //LPCRITICAL_SECTION cs;  

18.   

19. const int BUFFER_MAX_LEN = 1024;  

20. char bufW[BUFFER_MAX_LEN] = "hello client!";  

21. char bufR[BUFFER_MAX_LEN] = "";  

22. DWORD dwLen;  

23.   

24.   

25. HANDLE hThreadGet;  

26. HANDLE hThreadSend;  

27.   

28. WCHAR* toWChar(const char *c)  

29. {  

30.     WCHAR wszClassName[256];  

31.     memset(wszClassName, 0, sizeof(wszClassName));  

32.     MultiByteToWideChar(CP_ACP, 0, c, strlen(c) + 1, wszClassName, sizeof(wszClassName) / sizeof(wszClassName[0]));  

33.   

34.     return wszClassName;  

35. }  

36.   

37. DWORD WINAPI beginSendThread(PVOID p)  

38. {  

39.     printf("服务器send\n");  

40.     printf("等待连接...\n");  

41.   

42.     HANDLE hPipe = CreateNamedPipe(strPipeSend, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,  

43.         PIPE_UNLIMITED_INSTANCES, 0, 0, NMPWAIT_WAIT_FOREVER, 0);  

44.   

45.     if (ConnectNamedPipe(hPipe, NULL) != NULL)  

46.     {  

47.         printf("连接成功,开始发送缓冲区数据\n");  

48.         while (true)  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值