经常用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端发送的计算机使用信息)
- #include <stdio.h>
- #include <winsock.h>
- #pragma comment(lib, "wsock32")
- typedef struct
- {
- char ComputerName[30];
- char UserName[30];
- UINT CPURate;
- }COMPUTER_INFORM;
- int main()
- {
- /* start WSA */
- WSADATA wsaData;
- int iResult;
- iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
- if (iResult != NO_ERROR)
- {
- printf("Error at WSAStartup()/n");
- return 0;
- }
- /* Create socket */
- SOCKET sktSrv;
- sktSrv = socket(AF_INET, SOCK_DGRAM, 0 );
- if( sktSrv == INVALID_SOCKET )
- {
- printf("Error at socket()/n");
- return 0;
- }
- /* Create address */
- SOCKADDR_IN addrSrv;
- addrSrv.sin_family = AF_INET;
- addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
- addrSrv.sin_port = htons(4345);
- /* Bind socket */
- int result = bind(sktSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
- if(result == SOCKET_ERROR)
- {
- printf("Error at bind() : %d/n", WSAGetLastError());
- return 0;
- }
- /* Receive data */
- COMPUTER_INFORM info;
- SOCKADDR addrClt;
- int addrLen, recvLen;
- UINT index;
- recvLen = -1;
- index = 0;
- addrLen = sizeof(SOCKADDR);
- printf("Begin to receive/n");
- while(1)
- {
- recvLen = recvfrom(sktSrv, (char *)&info, sizeof(info), 0, (SOCKADDR *)&addrClt, &addrLen);
- // Add your process for "info"
- printf("%d, %s: %s, %3.1d%%/n", index, info.ComputerName, info.UserName, info.CPURate);
- index ++;
- }
- /* Close socket */
- closesocket(sktSrv);
- WSACleanup();
- return 0;
- }
Client端代码如下: (功能 - 获取本地机的计算机名、用户名、CPU使用率等信息,发送到Server)
- #include <stdio.h>
- #include <winsock.h>
- #pragma comment(lib, "wsock32")
- #define ADDR_SOCKET_SRV "192.168.0.117"
- #define APP_SOCKET_PORT 4545
- #define SERVER_UPDATE_INTERVAL 60000 // ms
- #define CLIENT_UPDATE_INTERVAL 6000 // ms
- #define SystemBasicInformation 0
- #define SystemPerformanceInformation 2
- #define SystemTimeInformation 3
- #define Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))
- typedef struct
- {
- char ComputerName[30];
- char UserName[30];
- UINT CPURate;
- }COMPUTER_INFORM;
- typedef struct
- {
- LARGE_INTEGER liIdleTime;
- DWORD dwSpare[76];
- } SYSTEM_PERFORMANCE_INFORMATION;
- typedef struct
- {
- DWORD dwUnknown1;
- ULONG uKeMaximumIncrement;
- ULONG uPageSize;
- ULONG uMmNumberOfPhysicalPages;
- ULONG uMmLowestPhysicalPage;
- ULONG uMmHighestPhysicalPage;
- ULONG uAllocationGranularity;
- PVOID pLowestUserAddress;
- PVOID pMmHighestUserAddress;
- ULONG uKeActiveProcessors;
- BYTE bKeNumberProcessors;
- BYTE bUnknown2;
- WORD wUnknown3;
- } SYSTEM_BASIC_INFORMATION;
- typedef struct
- {
- LARGE_INTEGER liKeBootTime;
- LARGE_INTEGER liKeSystemTime;
- LARGE_INTEGER liExpTimeZoneBias;
- ULONG uCurrentTimeZoneId;
- DWORD dwReserved;
- } SYSTEM_TIME_INFORMATION;
- typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);
- void main(void)
- {
- SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo;
- SYSTEM_TIME_INFORMATION SysTimeInfo;
- SYSTEM_BASIC_INFORMATION SysBaseInfo;
- double dbIdleTime;
- double dbSystemTime;
- LONG status;
- LARGE_INTEGER liOldIdleTime = {0,0};
- LARGE_INTEGER liOldSystemTime = {0,0};
- COMPUTER_INFORM ComputerInfo;
- SOCKET m_sockClt=0;
- char ComputerName[30];
- char UserName[30];
- DWORD size=30;
- WSADATA wsaData;
- sockaddr_in clientService;
- int ret;
- int iResult;
- PROCNTQSI NtQuerySystemInformation;
- iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
- if (iResult != NO_ERROR)
- {
- printf("Error at WSAStartup()/n");
- return;
- }
- memset(&ComputerInfo,0,sizeof(COMPUTER_INFORM));
- /* Init the client Socket */
- m_sockClt = socket(AF_INET, SOCK_DGRAM, 0);
- if(m_sockClt == INVALID_SOCKET)
- {
- printf("Create Client Socket Error %d!/n",WSAGetLastError());
- return;
- }
- /* Connect to server */
- clientService.sin_family = AF_INET;
- clientService.sin_addr.s_addr = inet_addr(ADDR_SOCKET_SRV); //inet_addr("192.168.0.117" );
- clientService.sin_port = htons(APP_SOCKET_PORT); //htons( 10500 );
- while(1)
- {
- NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(
- GetModuleHandle("ntdll"),
- "NtQuerySystemInformation"
- );
- if (!NtQuerySystemInformation)
- {
- continue;
- }
- else
- {
- break;
- }
- }
- while(1)
- {
- /* Get Number of Processors in the system */
- status = NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL);
- if (status != NO_ERROR)
- {
- continue;
- }
- else
- {
- break;
- }
- }
- /* Get Computer Name */
- if(!GetComputerName(ComputerName,&size))
- {
- printf("Failed 1/n");
- strcpy(ComputerInfo.UserName,"EMPTY");
- }
- else
- {
- printf("The Computer Name is :%s/n",ComputerName);
- strcpy(ComputerInfo.ComputerName,ComputerName);
- }
- printf("/nCPU Usage (press any key to exit): /n");
- UINT index = 0;
- while(1)
- {
- /* Get New System Time */
- status = NtQuerySystemInformation(SystemTimeInformation,&SysTimeInfo,sizeof(SysTimeInfo),0);
- if (status!=NO_ERROR)
- return;
- /* Get new CPU's idle time */
- status = NtQuerySystemInformation(SystemPerformanceInformation,&SysPerfInfo,sizeof(SysPerfInfo),NULL);
- if (status != NO_ERROR)
- return;
- /* if it's a first call - skip it */
- if (liOldIdleTime.QuadPart != 0)
- {
- /* CurrentValue = NewValue - OldValue */
- dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
- dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);
- /* CurrentCpuIdle = IdleTime / SystemTime */
- dbIdleTime = dbIdleTime / dbSystemTime;
- /* CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors */
- dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5;
- if(dbIdleTime < 0)
- {
- dbIdleTime = -dbIdleTime;
- }
- //printf("/b/b/b/b%3d%%/n",(UINT)dbIdleTime);
- //printf("index = %d/t", index);
- /* Get User Name */
- if(!GetUserName(UserName,&size))
- {
- printf("Failed 2/n");
- //strcpy(ComputerInfo.UserName,"EMPTY");
- continue;
- }
- else
- {
- //printf("User Name : %s/t",UserName);
- strcpy(ComputerInfo.UserName,UserName);
- }
- /* Write the CPU usage rate to the struct */
- ComputerInfo.CPURate = (UINT)dbIdleTime;
- //printf("%4.1d%%/n",(UINT)dbIdleTime);
- //ret = send(m_CSocket,(char *)&ComputerInfo,sizeof(ComputerInfo),0);
- printf("%d, %s: %s, %3.1d%%/n",
- index, ComputerInfo.ComputerName, ComputerInfo.UserName, ComputerInfo.CPURate);
- ret = sendto(m_sockClt, (char *)&ComputerInfo, sizeof(ComputerInfo), 0,
- (SOCKADDR *)&clientService, sizeof(SOCKADDR));
- if(ret == SOCKET_ERROR)
- {
- printf("Send Computer Information Error!/n");
- //goto Repeat;
- }
- }
- index ++;
- /* store new CPU's idle and system time */
- liOldIdleTime = SysPerfInfo.liIdleTime;
- liOldSystemTime = SysTimeInfo.liKeSystemTime;
- /* wait one minute */
- //Sleep(6000);
- Sleep(CLIENT_UPDATE_INTERVAL);
- }
- printf("/n");
- }