前言
前几天,用UDP发通知类的包, 还要去msdn去找资料.
贴一段代码,以后可以直接用.
udp允许丢包, 服务端只收小包, 不回答. 客户端只发小包.
记录
udp server
// EchoUDPServerDemo.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// 连接到winsock2对应的lib文件: Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 512 // 默认缓冲区长度为512, 数据报
#define DEFAULT_UDP_PORT "12345" // 默认服务器端口号为12345
#pragma pack(push)
#pragma pack(1)
typedef struct _tag_log_info {
char sz_type[32]; // 类型
char datetime[32]; // yyyy-mm-dd hh:mm:ss
char sz_content[DEFAULT_BUFLEN - 32 * 2]; //内容
} TAG_LOG_INFO;
typedef struct _tag_recv_udp_datagram {
union {
char reserve[DEFAULT_BUFLEN];
TAG_LOG_INFO log_info;
};
} TAG_RECV_UDP_DATAGRAM;
#pragma pack(pop)
int __cdecl main(void)
{
WSADATA wsaData;
int iResult;
SOCKET ServerSocket = INVALID_SOCKET;
struct addrinfo* result = NULL;
struct addrinfo hints;
// int iSendResult;
// char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
sockaddr_in clientaddr;
int clientlen = sizeof(sockaddr_in);
TAG_RECV_UDP_DATAGRAM RecvInfo;
// 初始化 Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
//声明IPv4地址族,数据报套接字,UDP协议
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_PASSIVE;
// 解析服务器地址和端口号
iResult = getaddrinfo(NULL, DEFAULT_UDP_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// 为面向连接的服务器创建套接字
ServerSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ServerSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// 为套接字绑定地址和端口号
iResult = bind(ServerSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ServerSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
printf("UDP server starting, port[%d]\n", atoi(DEFAULT_UDP_PORT));
do {
ZeroMemory(&clientaddr, sizeof(clientaddr));
ZeroMemory(&RecvInfo, sizeof(RecvInfo));
clientlen = sizeof(sockaddr_in);
iResult = recvfrom(ServerSocket, (char*)&RecvInfo, sizeof(RecvInfo), 0, (SOCKADDR*)&clientaddr, &clientlen);
if (iResult > 0) {
//情况1:成功接收到数据
printf("Bytes received: [%d] [%s][%s][%s]\n",
iResult, RecvInfo.log_info.datetime, RecvInfo.log_info.sz_type, RecvInfo.log_info.sz_content);
// 如果是作为日志服务器, 心跳检测, 客户端上线列表, 可以在收到短消息后, 不用回应客户端
//将缓冲区的内容回送给客户端
// iSendResult = sendto( ServerSocket, recvbuf, iResult, 0, (SOCKADDR *)&clientaddr,clientlen );
// if (iSendResult == SOCKET_ERROR)
// {
// printf("send failed with error: %d\n", WSAGetLastError());
// closesocket(ServerSocket);
// WSACleanup();
// return 1;
// }
// printf("Bytes sent: %d\n", iSendResult);
} else if (iResult == 0) {
//情况2:连接关闭
printf("Connection closing...\n");
} else {
//情况3:接收发生错误
printf("recv failed with error: %d\n", WSAGetLastError());
break;
}
} while (1);
// cleanup
closesocket(ServerSocket);
WSACleanup();
return 0;
}
/** run result
UDP server starting, port[12345]
Bytes received: [512] [2017-4-29 10:18:9][message][sn = 0]
Bytes received: [512] [2017-4-29 10:18:9][warning][sn = 1]
Bytes received: [512] [2017-4-29 10:18:9][error][sn = 2]
Bytes received: [512] [2017-4-29 10:18:9][message][sn = 3]
Bytes received: [512] [2017-4-29 10:18:9][warning][sn = 4]
Bytes received: [512] [2017-4-29 10:18:9][error][sn = 5]
*/
udp client
// udpClient.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#define RC_ERR -1
#define RC_OK 0
#define DEFAULT_BUFLEN 512 // 默认缓冲区长度为512, 数据报
#define DEFAULT_UDP_SERVER_IP "192.168.2.60"
#define DEFAULT_UDP_PORT "12345" // 默认服务器端口号为12345
#pragma pack(push)
#pragma pack(1)
typedef struct _tag_log_info {
char sz_type[32]; // 类型
char datetime[32]; // yyyy-mm-dd hh:mm:ss
char sz_content[DEFAULT_BUFLEN - 32 * 2]; //内容
} TAG_LOG_INFO;
typedef struct _tag_recv_udp_datagram {
union {
char reserve[DEFAULT_BUFLEN];
TAG_LOG_INFO log_info;
};
} TAG_RECV_UDP_DATAGRAM;
#pragma pack(pop)
int g_sockfd = -1;
int sock_init();
int sock_uninit();
int sock_send_udp_data(TAG_RECV_UDP_DATAGRAM* pData);
int main(int argc, char* argv[])
{
int i = 0;
SYSTEMTIME systm;
TAG_RECV_UDP_DATAGRAM Data;
sock_init();
for (i = 0; i < 6; i++) {
GetLocalTime(&systm);
sprintf(Data.log_info.datetime, "%d-%d-%d %d:%d:%d",
systm.wYear, systm.wMonth, systm.wDay, systm.wHour, systm.wMinute, systm.wSecond);
switch (i % 3) {
case 0:
strcpy(Data.log_info.sz_type, "message");
break;
case 1:
strcpy(Data.log_info.sz_type, "warning");
break;
case 2:
strcpy(Data.log_info.sz_type, "error");
break;
default:
strcpy(Data.log_info.sz_type, "log");
break;
}
sprintf(Data.log_info.sz_content, "sn = %d", i);
sock_send_udp_data(&Data);
}
sock_uninit();
return 0;
}
int sock_send_udp_data(TAG_RECV_UDP_DATAGRAM* pData)
{
int iRc = 0;
struct sockaddr_in dest_addr;
char szMsg[4096 + 32 * 3] = {'\0'};
if (NULL == pData) {
return RC_ERR;
}
if (-1 == g_sockfd) {
if ((g_sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
return RC_ERR;
}
}
memset(&dest_addr, 0, sizeof(dest_addr));
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(atoi(DEFAULT_UDP_PORT));
dest_addr.sin_addr.s_addr = inet_addr(DEFAULT_UDP_SERVER_IP);
iRc = sendto(g_sockfd, (char*)pData, sizeof(TAG_RECV_UDP_DATAGRAM), 0, (SOCKADDR*)&dest_addr, sizeof(dest_addr));
if (SOCKET_ERROR == iRc) {
printf("sendto failed with error: %d\n", WSAGetLastError());
closesocket(g_sockfd);
g_sockfd = -1;
return RC_ERR;
}
return RC_OK;
}
int sock_init()
{
WSADATA wsd;
if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) {
return RC_ERR;
}
if ((g_sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
return RC_ERR;
}
return RC_OK;
}
int sock_uninit()
{
if (-1 != g_sockfd) {
closesocket(g_sockfd);
g_sockfd = -1;
}
return RC_OK;
}