VC環境下UDP Socket程式碼
伺服器框架函數:
socket(); bind(); recfrom(); sendto(); closesocket();
客戶端框架函數:
socket(); recfrom(); sendto(); closesocket();
1)首先要打開伺服器進行監聽,所以伺服器server程式碼如下:
// udpse.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <winsock2.h> #pragma comment(lib,"WS2_32.lib") #include <iostream> int main(int argc, char* argv[]) { WSADATA wsaData; //初始化socket WSAStartup(MAKEWORD(2,2),&wsaData); //建立socket SOCKET recvSocket; recvSocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); //將socket進行綁定 sockaddr_in reAddr; reAddr.sin_family=AF_INET; reAddr.sin_port=htons(5678); reAddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY); bind(recvSocket,(sockaddr *)&reAddr,sizeof(reAddr)); //調用recvfrom函數綁定在socket接收到客戶機數據 //獲取目前系統時間 sDataTime, SYSTEMTIME st; GetLocalTime(&st); //char sDataTime[30]; printf("當前系統伺服器時間:%4d-%2d-%2d %2d:%2d:%2d\n",st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st. wSecond); char recvBuf[1024]; int bufLen=1024; //兩個暫時沒用的,客戶端屬性 sockaddr_in FromclientAddr; int FromclientSize=sizeof(FromclientAddr); int lbuf=recvfrom(recvSocket,recvBuf,bufLen,0,(SOCKADDR *)&FromclientAddr,&FromclientSize); recvBuf[lbuf]='\0'; printf("客戶端IP地址是:%s,端口是:%d\n,發來的數據內容是:%s\n",inet_ntoa(FromclientAddr.sin_addr),FromclientAddr.sin_port,recvBuf); printf("接收完成,關閉socket\n"); closesocket(recvSocket); //釋放資源並退出 WSACleanup(); return 0; }
2)客戶端發送數據
// udp.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <winsock2.h> #pragma comment(lib,"WS2_32.lib") int main(int argc, char* argv[]) { WSADATA wsaData; //初始化socket WSAStartup(MAKEWORD(2,2),&wsaData); //套接初始化 SOCKET sendSocket; sendSocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); //設置即將連伺服器地址 sockaddr_in seAddr; seAddr.sin_family=AF_INET; seAddr.sin_port=htons(5678); seAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");//;htonl(INADDR_ANY) //初始化 char sendBuf[1024]="hello wang shu qing"; int bufLen=1024; //向伺服器發送數據 printf("請輸入發送數據給伺服器:\n"); scanf("%s",sendBuf); bufLen=strlen(sendBuf); //綁定 sendto(sendSocket,sendBuf,bufLen,0,(SOCKADDR *)&seAddr,sizeof(seAddr)); //發送完成,關閉socket printf("發送完成,關閉socket\n"); closesocket(sendSocket); //釋放資源並退出 WSACleanup(); return 0; }
熱門評論