工程环境: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)