这是C++ SOCKET网络程序中的C/S结构之UDP "Hello World !",共两个控制台工程:
-
- #include <stdio.h>
- #include <WINSOCK2.H>
-
- #pragma comment(lib,"WS2_32.lib")
- #define BUF_SIZE 64
-
- int main(void)
- {
- WSADATA wsd;
- SOCKET s;
- int nRet;
-
-
- if(WSAStartup(MAKEWORD(2,2),&wsd) != 0)
- {
- printf("WSAStartup failed !/n");
- return 1;
- }
-
-
- s = socket(AF_INET,SOCK_DGRAM,0);
- if(s == INVALID_SOCKET)
- {
- printf("socket() failed ,Error Code:%d/n",WSAGetLastError());
- WSACleanup();
- return 1;
- }
-
- SOCKET socketSrv = socket(AF_INET,SOCK_DGRAM,0);
- SOCKADDR_IN addrSrv;
- SOCKADDR_IN addrClient;
- char buf[BUF_SIZE];
- int len = sizeof(SOCKADDR);
-
-
- ZeroMemory(buf,BUF_SIZE);
- addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
- addrSrv.sin_family = AF_INET;
- addrSrv.sin_port = htons(5000);
-
-
- nRet = bind(socketSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
- if(SOCKET_ERROR == nRet)
- {
- printf("bind failed !/n");
- closesocket(s);
- WSACleanup();
- return -1;
- }
-
-
- nRet = recvfrom(socketSrv,buf,BUF_SIZE,0,(SOCKADDR*)&addrClient,&len);
- if(SOCKET_ERROR == nRet)
- {
- printf("recvfrom failed !/n");
- closesocket(s);
- WSACleanup();
- return -1;
- }
-
- printf("Recv From Client:%s/n",buf);
-
-
- sendto(socketSrv,"UDP Hello World !",sizeof("UDP Hello World !"),0,(SOCKADDR*)&addrClient,len);
- closesocket(s);
- WSACleanup();
- return 0;
- }
-
- #include <stdio.h>
- #include <WINSOCK2.H>
-
- #pragma comment(lib,"WS2_32.lib")
- #define BUF_SIZE 64
-
- int main(void)
- {
- WSADATA wsd;
- SOCKET s;
-
-
- if(WSAStartup(MAKEWORD(2,2),&wsd) != 0)
- {
- printf("WSAStartup failed !/n");
- return 1;
- }
-
-
- s = socket(AF_INET,SOCK_DGRAM,0);
- if(s == INVALID_SOCKET)
- {
- printf("socket() failed, Error Code:%d/n",WSAGetLastError());
- WSACleanup();
- return 1;
- }
-
- char buf[BUF_SIZE];
- SOCKADDR_IN servAddr;
- SOCKET sockClient = socket(AF_INET,SOCK_DGRAM,0);
- int nRet;
-
- ZeroMemory(buf,BUF_SIZE);
- strcpy(buf,"UDP Hello World !");
-
-
- servAddr.sin_family = AF_INET;
- servAddr.sin_addr.S_un.S_addr = inet_addr("192.168.1.254");
- servAddr.sin_port = htons(5000);
-
-
- int nServAddLen = sizeof(servAddr);
- if(sendto(sockClient,buf,BUF_SIZE,0,(sockaddr *)&servAddr,nServAddLen) == SOCKET_ERROR)
- {
- printf("recvfrom() failed:%d/n",WSAGetLastError());
- closesocket(s);
- WSACleanup();
- return 1;
- }
- nRet = recvfrom(sockClient,buf,BUF_SIZE,0,(sockaddr *)&servAddr,&nServAddLen);
- if(SOCKET_ERROR == nRet)
- {
- printf("recvfrom failed !/n");
- closesocket(s);
- WSACleanup();
- return -1;
- }
-
-
- printf("Recv From Server:%s/n",buf);
- closesocket(s);
- WSACleanup();
- return 0;
- }
程序运行效果:
源代码下载地址:
http://www.rayfile.com/files/733c832e-a2d8-11de-a838-0014221b798a/
http://blog.csdn.net/wangningyu/article/details/4560835
|
请发表评论