两个控制台应用程序能传递消息么?

本文展示了C/C++环境下服务器与客户端通过消息传递进行通信的基本原理和实现方式,包括消息接收、处理和发送的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务器端
C/C++ code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "stdafx.h"
#include <windows.h>
#include <iostream>
using  namespace  std;
 
int  main( int  argc,  char * argv[])
{   
     cout<< "server start ..." <<endl;   
     MSG msg;
     while (GetMessage(&msg,NULL,0,0))          
     {  
         if (WM_USER+1000 == msg.message)
         {
             cout<< "get client msg and parameter is " <<msg.lParam<<endl;
         }
         TranslateMessage   (&msg)   ;          
         DispatchMessage   (&msg)   ;          
     }
     cout<< "server exit ..." <<endl;
     return  0;
}


客户端,注意我的服务器端是叫myserver的

C/C++ code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "stdafx.h"
#include <Windows.h>
#include <Tlhelp32.h>
#include <iostream>
 
using  namespace  std;
int  main( int  argc,  char * argv[])
{   
     HANDLE  hProcess = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
     PROCESSENTRY32 info;
     info.dwSize =  sizeof (PROCESSENTRY32);
     BOOL  bGetmore = Process32First(hProcess,&info);
     BOOL  bfind = FALSE;
     DWORD  taget = 0;
     
     while (bGetmore && !bfind)
     {
         if (0== strcmp ( "myserver.exe" ,info.szExeFile))
         {
             cout<< "process id " <<info.th32ProcessID<<endl;   
             HANDLE  hModule = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD,0);
             THREADENTRY32 tinfo;
             tinfo.dwSize =  sizeof (THREADENTRY32);
             bGetmore = Thread32First(hModule, &tinfo);
             while (bGetmore)
             {
                 if (info.th32ProcessID==tinfo.th32OwnerProcessID)
                 {
                     cout<< "thread id is " <<tinfo.th32ThreadID<<endl;
                     bfind = TRUE;
                     taget = tinfo.th32ThreadID;
                     break ;
                 }
                 bGetmore = Thread32Next(hModule,&tinfo);
             }
             CloseHandle(hModule);
             break ;
         }       
         bGetmore = Process32Next(hProcess, &info); 
     }
     CloseHandle(hProcess);
     if (!bfind)
     {
         return  0;
     }
     int  i = 0;
     while (1)
     {
         if (::PostThreadMessage(taget,WM_USER+1000,0,++i))
         {
             cout<< "send message " <<i<<endl;
         }
         else
         {
             cout<< "fail at " <<i<< "," <<GetLastError()<<endl;
         }   
         Sleep(1000);
     }
     return  0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值