一個最基本的UDP通信代碼例子

小例子代碼實現了基於udp 的socket通信。完成的功能如下:

1、          利用socket編程建立服務器與客戶端之間的UDP連接。

2、          完成C/S之間的數據通信,具體包括4點:
        ①  Client通過給定的Server IP和端口號向Server端發送請求。請求來自cmd命令行用戶輸入。
        ② Server端保持監聽狀態,收到Client端請求後,將請求內容輸出到命令行。
        ③ Server端每接收一次請求數據,即向發出請求的客戶端發送“OK”字符串,表示該請求已經Received。
        ④ Client端接收到“OK”字符串後即將其輸出到命令行。

服務器端代碼如下:

  1. //chang. exercise of UDP socket.  
  2. // Implements the function of send info between server and client.  
  3. //When this server is listening and a client send an request, it's will print the info on the cmd and reply a data:"OK".  
  4. //server.  
  5. #include "stdio.h"  
  6. #include "Winsock2.h"  
  7. #include "iostream"  
  8. #include "string"  
  9. //should add the under line if not add lib in the project.(appendicular dependent)  
  10. //#pragma comment(lib, "ws2_32.lib")  
  11.  
  12. //define host IP and usable port.  
  13. #define HOST_IP 127.0.0.1  
  14. #define HOST_PORT 8080  
  15. #define OK_STR "OK"  
  16.  
  17. void main(){  
  18.     //the version bit of Winsock  
  19.     int version_a = 1;//low bit  
  20.     int version_b = 1;//high bit  
  21.  
  22.     //makeword  
  23.     WORD versionRequest = MAKEWORD(version_a,version_b);  
  24.     WSAData wsaData;  
  25.     int err;  
  26.     //wsa startup  
  27.     err = WSAStartup(versionRequest, &wsaData);   
  28.  
  29.     if(err != 0 ){  
  30.         printf("ERROR!");  
  31.         return;  
  32.     }  
  33.     //check whether the version is 1.1, if not print the error and cleanup wsa?  
  34.     if (LOBYTE(wsaData.wVersion)  != 1 || HIBYTE(wsaData.wVersion) != 1)  
  35.     {  
  36.         printf("WRONG WINSOCK VERSION!");  
  37.         WSACleanup();  
  38.         return;  
  39.     }  
  40.  
  41.     /*  
  42.     *build the socket  
  43.     *first param is protocol family, generally AF_INET for IP internet.  
  44.     *second param is type of socket, SOCK_DGRAM is for Data Gram(UDP), and SOCK_STREAM is for TCP.  
  45.     *the last param is communicate protocol. Generally is zero.  
  46.     */ 
  47.     SOCKET socServer = socket(AF_INET, SOCK_DGRAM,0);  
  48.     //infomation of address, always NOT being operated directly.  
  49.     SOCKADDR_IN addr_Srv;  
  50.     //Struct sin_addr is  used to defind IP address,  it's a property of addr_in.  
  51.     //It's nest three structs as S_un_b, S_un_w and S-un.(union)  
  52.     addr_Srv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);  
  53.     //set protocol family  
  54.     addr_Srv.sin_family = AF_INET;  
  55.     //set host port  
  56.     addr_Srv.sin_port = htons(HOST_PORT);  
  57.  
  58.     //bind socket to  the host  
  59.     bind(socServer,( SOCKADDR*) &addr_Srv, sizeof(SOCKADDR));  
  60.  
  61.     //address  of a client  
  62.     SOCKADDR_IN addr_Clt;  
  63.     char recvBuf[100];  
  64.  
  65.     int fromlen = sizeof(SOCKADDR);  
  66.     // while() to listen all the time  
  67.     while(true){  
  68.         //receive data function of server  
  69.         recvfrom(socServer, recvBuf, 100, 0,  (SOCKADDR*) &addr_Clt, &fromlen);  
  70.         //output the data received to cmd  
  71.         std::cout<<recvBuf<<std::endl;  
  72.         //send "OK" to the from_client to indicates that data have been received.  
  73.         //send function is used by server, while sendto function is used by client. NOT sure.  
  74. //      send(addr_Clt, OK_STR,  strlen(OK_STR)+1, 0);  
  75.         sendto(socServer, OK_STR, strlen(OK_STR)+1, 0, (SOCKADDR*)&addr_Clt, sizeof(SOCKADDR));  
  76.     }  
  77.       
  78.     // at last close the socket.  
  79.     closesocket(socServer);  
  80.     //cleanup WSAData  
  81.     WSACleanup();} 

客戶端代碼如下:

  1. //chang. exercise of UDP socket.  
  2. // Implements the function of send info between server and client.  
  3. //When this server is listening and a client send an request, it's will print the info on the cmd and reply a data:"OK".  
  4. //client.  
  5. #include "Winsock2.h"  
  6. #include "iostream"  
  7. #include "stdio.h"  
  8. #pragma comment(lib, "ws2_32.lib")  
  9.  
  10.  
  11. #define HOST_IP "127.0.0.1"  
  12. #define HOST_PORT 8080  
  13.  
  14. void main(){  
  15.     //the version bit of Winsock  
  16.     int version_a = 1;//low bit  
  17.     int version_b = 1;//high bit  
  18.  
  19.     //makeword  
  20.     WORD versionRequest = MAKEWORD(version_a,version_b);  
  21.     WSAData wsaData;  
  22.     int error;  
  23.     error = WSAStartup(versionRequest, &wsaData);   
  24.  
  25.     if(error != 0   ){  
  26.         printf("ERROR!");  
  27.         return;  
  28.     }  
  29.     //check whether the version is 1.1, if not print the error and cleanup wsa?  
  30.     if (LOBYTE(wsaData.wVersion)  != 1 || HIBYTE(wsaData.wVersion) != 1)  
  31.     {  
  32.         printf("WRONG WINSOCK VERSION!");  
  33.         WSACleanup();  
  34.         return;  
  35.     }  
  36.  
  37.  
  38.     //request info obtained by user's input  
  39.     char requestStr[100];  
  40.  
  41.     //build a sockeet   
  42.     SOCKET socClient = socket(AF_INET, SOCK_DGRAM, 0);  
  43.     SOCKADDR_IN addrSrv;        // a instance of SOCKADDR_IN, which is used in format of SOCKADDR.  
  44.     addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");        //set the host IP  
  45.     addrSrv.sin_family=AF_INET;     //set the protocol family  
  46.     addrSrv.sin_port=htons(HOST_PORT);      //set the port number  
  47.  
  48.     // array to store the data that server feedback.  
  49.     char cRecvBuf[100];  
  50. //  int len=sizeof(SOCKADDR);  
  51.  
  52.     //while   
  53.     while(true){  
  54.             // gain info that user input  
  55.         std::cin>>requestStr;  
  56.         //sendto function is used to send programe data to the server  
  57.         sendto(socClient, requestStr, strlen(requestStr)+1, 0, (SOCKADDR*) &addrSrv, sizeof(SOCKADDR));  
  58.  
  59.         //receive the feedback info from server  
  60.         //recv function is used in client.  
  61.         recv(socClient, cRecvBuf, strlen(cRecvBuf)+1, 0);  
  62.         //output the cRecvBuf to cmd  
  63.         std::cout<< cRecvBuf << std::endl;  
  64.     }  
  65.       
  66.     //close the socket and cleanup the wsadata  
  67.     closesocket(socClient);  
  68.     WSACleanup();  
  69.  
  70. //  return 0;  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章