UDP时间更新服务程序
http://qzher.com/?p=647
网络编程,最好采用两台电脑,
或者一台电脑,再开个虚拟机,虚拟机采用网络桥接模式
特点:
发消息方一直向指定IP发送报时消息
收方一上线就能得到发来的即时消息 (未上线的消息全被抛弃)
若收方上线期间, 发消息方关闭, 收方也一直等待发消息方的消息,
只要发消息方一上线发送消息,收方可以继续接收发来的消息
应用: 比如视频直播,游戏画面等的传输
源码:
#include <stdio.h>
#include<iostream>
#include <Winsock2.h>
#include <time.h>
#pragma comment(lib,"ws2_32.lib")
#define BUF_SIZE 64
int main()
{
WSADATA wsadata;
int nRes = 0;
nRes = WSAStartup(MAKEWORD(2, 3), &wsadata);
if (0 != nRes)
{
return 0;
}
SOCKET sockSend;
sockSend = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (INVALID_SOCKET == sockSend)
{
WSACleanup();
return 0;
}
sockaddr_in addrRecv;
addrRecv.sin_family = AF_INET;
addrRecv.sin_port = htons(9090);
// 向222的IP发送数据
addrRecv.sin_addr.S_un.S_addr = inet_addr("192.168.1.222");
// 就算绑定错误也不用管(这里应该也会绑定出错)
nRes = bind(sockSend, (sockaddr*)&addrRecv, sizeof(sockaddr_in));
printf("—-时间服务器已启动—–\n ");
int nSendLen = 0;
struct tm tLocal;
time_t t = time(NULL);
char chTime[64];
int nLen = sizeof(sockaddr_in);
while (true)
{
// 获取当前时间并格式化
t = time(NULL);
localtime_s(&tLocal, &t);
sprintf_s(chTime, "%s", asctime(&tLocal));
// 向222发送时间
nSendLen = sendto(sockSend, chTime, strlen(chTime), 0, (sockaddr*)&addrRecv, nLen);
Sleep(1000);
}
closesocket(sockSend);
WSACleanup();
std::cout << "server stoped! " << std::endl;
return 0;
}
#include <stdio.h>
#include<iostream>
#include <Winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#define BUF_SIZE 64
int main()
{
WSADATA wsadata;
int nRes = 0;
nRes = WSAStartup(MAKEWORD(2, 2), &wsadata);
if (0 != nRes)
{
return 0;
}
SOCKET sockTimeRecv;
sockTimeRecv = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (INVALID_SOCKET == sockTimeRecv)
{
WSACleanup();
return 0;
}
sockaddr_in addrRecv;
addrRecv.sin_family = AF_INET;
addrRecv.sin_port = htons(9090);
addrRecv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
nRes = bind(sockTimeRecv, (sockaddr*)&addrRecv, sizeof(sockaddr_in));
char chBufRecv[BUF_SIZE] = { "0" };
int nLen = sizeof(sockaddr_in);
printf("—-qzher.com start to recv data—–\n ");
char* pChClientAddr = nullptr;
int nRecvLen = 0;
while (true)
{
nRecvLen = recvfrom(sockTimeRecv, chBufRecv, BUF_SIZE, 0,
(sockaddr*)&addrRecv, &nLen);
if (strlen(chBufRecv) > 0)
{
pChClientAddr = inet_ntoa(addrRecv.sin_addr);
printf("%s send:———%s\n", pChClientAddr, chBufRecv);
}
}
closesocket(sockTimeRecv);
WSACleanup();
std::cout << "server stoped! " << std::endl;
return 0;
}
源码下载: (VS2015) http://download.csdn.net/detail/sinat_35523212/9615378