通过传时间实现UDP对时
2012-05-15 09:51:24 来源:WEB开发网核心提示: UDP对时服务器端#include <winsock2.h>#pragma comment(lib,"WS2_32.lib")WSADATA wsd;SOCKET s;char buf[1024];if(WSAStartup(MAKEWORD(2,2),&wsd)!=0){return
UDP对时服务器端
#include <winsock2.h> #pragma comment(lib,"WS2_32.lib") WSADATA wsd; SOCKET s; char buf[1024]; if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { return -1;//失败 } s=socket(AF_INET,SOCK_DGRAM,0); if(s==INVALID_SOCKET) { WSACleanup(); return -1;//创建套接字失败 } SOCKADDR_IN servAddr; servAddr.sin_family=AF_INET; servAddr.sin_addr.s_addr=inet_addr("127.0.0.1"); servAddr.sin_port=htons(5000); if(bind(s,(SOCKADDR*)&servAddr,sizeof(SOCKADDR_IN))==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//绑定套接字失败 } int nServAddrlen=sizeof(servAddr); ZeroMemory(buf,sizeof(buf)); if(recvfrom(s,buf,sizeof(buf),0,(SOCKADDR*)&servAddr,&nServAddrlen)==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//接收数据失败 } CString str(buf); if(str=="TimeNow") { SOCKADDR_IN clientAddr; clientAddr.sin_family=AF_INET; clientAddr.sin_addr.s_addr=inet_addr("127.0.0.1"); clientAddr.sin_port=htons((short)2000); int nClientlen=sizeof(clientAddr); SYSTEMTIME systime; GetLocalTime(&systime); if(sendto(s,(char *)&systime,sizeof(SYSTEMTIME),0,(SOCKADDR*)&clientAddr,nClientlen)==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//向服务器发送数据失败 } } closesocket(s); WSACleanup();
UDP对时客户端
#include <winsock2.h> #pragma comment(lib,"WS2_32.lib") WSADATA wsd; SOCKET s; char buf[1024]; if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { return -1;//失败 } s=socket(AF_INET,SOCK_DGRAM,0); if(s==INVALID_SOCKET) { WSACleanup(); return -1;//创建套接字失败 } SOCKADDR_IN servAddr; servAddr.sin_family=AF_INET; servAddr.sin_addr.s_addr=inet_addr("127.0.0.1"); servAddr.sin_port=htons(2000); if(bind(s,(SOCKADDR*)&servAddr,sizeof(SOCKADDR_IN))==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//绑定套接字失败 } int nServAddrlen=sizeof(servAddr); ZeroMemory(buf,sizeof(buf)); CString ss="TimeNow"; strcpy(buf,ss); SOCKADDR_IN clientAddr; clientAddr.sin_family=AF_INET; clientAddr.sin_addr.s_addr=inet_addr("127.0.0.1"); clientAddr.sin_port=htons((short)5000); int nClientlen=sizeof(clientAddr); if(sendto(s,buf,sizeof(buf),0,(SOCKADDR*)&clientAddr,nClientlen)==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//向服务器发送数据失败 } memset(buf,0,1024); if(recvfrom(s,buf,sizeof(buf),0,(SOCKADDR*)&servAddr,&nServAddrlen)==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//接收数据失败 } SYSTEMTIME systime; memcpy(&systime,buf,16); SetLocalTime(&systime);//设置本地与服务器时间同步。 closesocket(s); WSACleanup();
更多精彩
赞助商链接