UDP socket (UDP套接口通信)

经常用TCP套接口通信,UDP套接口也是很重要。今天使用了一下,小节如下:


无论是 Server 还是 Client,首先包含头文件和库

#include <winsock.h>
#pragma comment(lib, "wsock32")


对于创建Server:
1. WSAStartup() 加载套接字库
2. socket() 创建套接字 
3. bind() 绑定
4. recvfrom() 接收 / sendto() 发送
5. closesocket() 关闭套接字
6. WSACleanup() 卸载套接字库


对于创建Client:  (不需要bind)
1. WSAStartup() 加载套接字库
2. socket() 创建套接字 
3. recvfrom() 接收 / sendto() 发送
4. closesocket() 关闭套接字
5. WSACleanup() 卸载套接字库

Server端代码如下:(功能 - 接收从Client端发送的计算机使用信息)
  1. #include <stdio.h>
  2. #include <winsock.h>
  3. #pragma comment(lib, "wsock32")
  4. typedef struct
  5. {
  6.     char ComputerName[30];
  7.     char UserName[30];
  8.     UINT CPURate;
  9. }COMPUTER_INFORM;
  10. int main()
  11. {
  12.     /*  start WSA   */
  13.     WSADATA wsaData;
  14.     int iResult;
  15.     
  16.     iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
  17.     if (iResult != NO_ERROR)
  18.     {
  19.         printf("Error at WSAStartup()/n");
  20.         return 0;
  21.     }
  22.     /*  Create socket   */
  23.     SOCKET sktSrv;
  24.     sktSrv = socket(AF_INET, SOCK_DGRAM, 0 );
  25.     if( sktSrv == INVALID_SOCKET )
  26.     {
  27.         printf("Error at socket()/n");
  28.         return 0;
  29.     }
  30.     /*  Create address  */
  31.     SOCKADDR_IN addrSrv;
  32.     addrSrv.sin_family = AF_INET;
  33.     addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
  34.     addrSrv.sin_port = htons(4345);
  35.     /*  Bind socket */
  36.     int result = bind(sktSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
  37.     if(result == SOCKET_ERROR)
  38.     {
  39.         printf("Error at bind() : %d/n", WSAGetLastError());
  40.         return 0;
  41.     }
  42.     /*  Receive data    */
  43.     COMPUTER_INFORM info;
  44.     SOCKADDR addrClt;
  45.     int addrLen, recvLen;
  46.     UINT index;
  47.     recvLen = -1;
  48.     index = 0;
  49.     addrLen = sizeof(SOCKADDR);
  50.     printf("Begin to receive/n");
  51.     while(1)
  52.     {
  53.         recvLen = recvfrom(sktSrv, (char *)&info, sizeof(info), 0, (SOCKADDR *)&addrClt, &addrLen);
  54.         // Add your process for "info"
  55.         printf("%d, %s: %s, %3.1d%%/n", index, info.ComputerName, info.UserName, info.CPURate);
  56.         index ++;
  57.     }
  58.     /*  Close socket    */
  59.     closesocket(sktSrv);
  60.     WSACleanup();
  61.     return 0;
  62. }
Client端代码如下: (功能 - 获取本地机的计算机名、用户名、CPU使用率等信息,发送到Server)
  1. #include <stdio.h>
  2. #include <winsock.h>
  3. #pragma comment(lib, "wsock32")
  4. #define ADDR_SOCKET_SRV     "192.168.0.117"
  5. #define APP_SOCKET_PORT     4545
  6. #define SERVER_UPDATE_INTERVAL      60000   //  ms
  7. #define CLIENT_UPDATE_INTERVAL      6000    //  ms
  8. #define SystemBasicInformation       0
  9. #define SystemPerformanceInformation 2
  10. #define SystemTimeInformation        3
  11. #define Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))
  12. typedef struct
  13. {
  14.     char ComputerName[30];
  15.     char UserName[30];
  16.     UINT CPURate;
  17. }COMPUTER_INFORM;
  18. typedef struct
  19. {
  20.     LARGE_INTEGER   liIdleTime;
  21.     DWORD           dwSpare[76];
  22. } SYSTEM_PERFORMANCE_INFORMATION;
  23. typedef struct
  24. {
  25.     DWORD   dwUnknown1;
  26.     ULONG   uKeMaximumIncrement;
  27.     ULONG   uPageSize;
  28.     ULONG   uMmNumberOfPhysicalPages;
  29.     ULONG   uMmLowestPhysicalPage;
  30.     ULONG   uMmHighestPhysicalPage;
  31.     ULONG   uAllocationGranularity;
  32.     PVOID   pLowestUserAddress;
  33.     PVOID   pMmHighestUserAddress;
  34.     ULONG   uKeActiveProcessors;
  35.     BYTE    bKeNumberProcessors;
  36.     BYTE    bUnknown2;
  37.     WORD    wUnknown3;
  38. } SYSTEM_BASIC_INFORMATION;
  39. typedef struct
  40. {
  41.     LARGE_INTEGER liKeBootTime;
  42.     LARGE_INTEGER liKeSystemTime;
  43.     LARGE_INTEGER liExpTimeZoneBias;
  44.     ULONG         uCurrentTimeZoneId;
  45.     DWORD         dwReserved;
  46. } SYSTEM_TIME_INFORMATION;
  47. typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);
  48. void main(void)
  49. {
  50.     SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo;
  51.     SYSTEM_TIME_INFORMATION        SysTimeInfo;
  52.     SYSTEM_BASIC_INFORMATION       SysBaseInfo;
  53.     double                         dbIdleTime;
  54.     double                         dbSystemTime;
  55.     LONG                           status;
  56.     LARGE_INTEGER                  liOldIdleTime = {0,0};
  57.     LARGE_INTEGER                  liOldSystemTime = {0,0};
  58.     COMPUTER_INFORM                ComputerInfo;
  59.     SOCKET                         m_sockClt=0;
  60.     char                           ComputerName[30]; 
  61.     char                           UserName[30];
  62.     DWORD                          size=30;  
  63.     WSADATA                        wsaData;
  64.     sockaddr_in                    clientService; 
  65.     int                            ret;
  66.     int                            iResult;
  67.     PROCNTQSI NtQuerySystemInformation;
  68.     iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
  69.     if (iResult != NO_ERROR)
  70.     {
  71.         printf("Error at WSAStartup()/n");
  72.         return;
  73.     }
  74.     memset(&ComputerInfo,0,sizeof(COMPUTER_INFORM));
  75.     /* Init the client Socket */
  76.     m_sockClt = socket(AF_INET, SOCK_DGRAM, 0);
  77.     if(m_sockClt == INVALID_SOCKET)
  78.     {           
  79.        printf("Create Client Socket Error %d!/n",WSAGetLastError());
  80.        return;
  81.     }
  82.     /* Connect to server */
  83.     clientService.sin_family = AF_INET;
  84.     clientService.sin_addr.s_addr = inet_addr(ADDR_SOCKET_SRV); //inet_addr("192.168.0.117" );
  85.     clientService.sin_port = htons(APP_SOCKET_PORT);    //htons( 10500 );
  86.     while(1)
  87.     {
  88.         NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(
  89.                                           GetModuleHandle("ntdll"),
  90.                                          "NtQuerySystemInformation"
  91.                                          );
  92.         if (!NtQuerySystemInformation)
  93.         {
  94.             continue;
  95.         }
  96.         else
  97.         {
  98.             break;
  99.         }
  100.     }
  101.     while(1)
  102.     {
  103.         /* Get Number of Processors in the system */
  104.         status = NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL);
  105.         if (status != NO_ERROR)
  106.         {
  107.             continue;
  108.         }
  109.         else
  110.         {
  111.             break;
  112.         }
  113.     }
  114.     
  115.     /* Get Computer Name */
  116.     if(!GetComputerName(ComputerName,&size))   
  117.     {   
  118.         printf("Failed 1/n");
  119.         strcpy(ComputerInfo.UserName,"EMPTY");
  120.     }
  121.     else
  122.     {
  123.         printf("The Computer Name is :%s/n",ComputerName);
  124.         strcpy(ComputerInfo.ComputerName,ComputerName);
  125.     }
  126.     printf("/nCPU Usage (press any key to exit):    /n");
  127.     UINT index = 0;
  128.     while(1)
  129.     {
  130.         
  131.         /* Get New System Time */
  132.         status = NtQuerySystemInformation(SystemTimeInformation,&SysTimeInfo,sizeof(SysTimeInfo),0);
  133.         if (status!=NO_ERROR)
  134.             return;
  135.         /* Get new CPU's idle time */
  136.         status = NtQuerySystemInformation(SystemPerformanceInformation,&SysPerfInfo,sizeof(SysPerfInfo),NULL);
  137.         if (status != NO_ERROR)
  138.             return;
  139.         /* if it's a first call - skip it */
  140.        if (liOldIdleTime.QuadPart != 0)
  141.        {
  142.             /* CurrentValue = NewValue - OldValue */
  143.             dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
  144.             dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);
  145.             /* CurrentCpuIdle = IdleTime / SystemTime */
  146.             dbIdleTime = dbIdleTime / dbSystemTime;
  147.             /* CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors */
  148.             dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5;
  149.             
  150.             if(dbIdleTime < 0)
  151.             {
  152.                 dbIdleTime = -dbIdleTime;
  153.             }
  154.             //printf("/b/b/b/b%3d%%/n",(UINT)dbIdleTime);
  155.             //printf("index = %d/t", index);
  156.             /* Get User Name */
  157.             if(!GetUserName(UserName,&size))
  158.             {   
  159.                 printf("Failed 2/n");
  160.                 //strcpy(ComputerInfo.UserName,"EMPTY");
  161.                 continue;
  162.             }
  163.             else
  164.             {
  165.                 //printf("User Name : %s/t",UserName);
  166.                 strcpy(ComputerInfo.UserName,UserName);
  167.             }
  168.             /* Write the CPU usage rate to the struct */
  169.             ComputerInfo.CPURate = (UINT)dbIdleTime;
  170.             //printf("%4.1d%%/n",(UINT)dbIdleTime);
  171.             //ret = send(m_CSocket,(char *)&ComputerInfo,sizeof(ComputerInfo),0);
  172.             printf("%d, %s: %s, %3.1d%%/n"
  173.                 index, ComputerInfo.ComputerName, ComputerInfo.UserName, ComputerInfo.CPURate);
  174.             ret = sendto(m_sockClt, (char *)&ComputerInfo, sizeof(ComputerInfo), 0, 
  175.                 (SOCKADDR *)&clientService, sizeof(SOCKADDR));
  176.             if(ret == SOCKET_ERROR)
  177.             {
  178.                 printf("Send Computer Information Error!/n");
  179.                 //goto Repeat;
  180.             }
  181.        }
  182.        index ++;
  183.         /* store new CPU's idle and system time */
  184.         liOldIdleTime = SysPerfInfo.liIdleTime;
  185.         liOldSystemTime = SysTimeInfo.liKeSystemTime;
  186.         /* wait one minute */
  187.         //Sleep(6000);
  188.         Sleep(CLIENT_UPDATE_INTERVAL);
  189.     }
  190.     printf("/n");
  191. }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值