Winsock使用之客户端和服务器完整代码

本节包含 TCP/IP 客户端和服务器应用程序的完整源代码︰

完整客户端源码

[cpp]  view plain  copy
  1. #define WIN32_LEAN_AND_MEAN  
  2.   
  3. #include <windows.h>  
  4. #include <winsock2.h>  
  5. #include <ws2tcpip.h>  
  6. #include <stdlib.h>  
  7. #include <stdio.h>  
  8.   
  9.   
  10. // Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib  
  11. #pragma comment (lib, "Ws2_32.lib")  
  12. #pragma comment (lib, "Mswsock.lib")  
  13. #pragma comment (lib, "AdvApi32.lib")  
  14.   
  15.   
  16. #define DEFAULT_BUFLEN 512  
  17. #define DEFAULT_PORT "27015"  
  18.   
  19. int __cdecl main(int argc, char **argv)  
  20. {  
  21.     WSADATA wsaData;  
  22.     SOCKET ConnectSocket = INVALID_SOCKET;  
  23.     struct addrinfo *result = NULL,  
  24.                     *ptr = NULL,  
  25.                     hints;  
  26.     char *sendbuf = "this is a test";  
  27.     char recvbuf[DEFAULT_BUFLEN];  
  28.     int iResult;  
  29.     int recvbuflen = DEFAULT_BUFLEN;  
  30.      
  31.     // Validate the parameters  
  32.      /*if (argc != 2) { 
  33.         printf("usage: %s server-name\n", argv[0]); 
  34.         return 1; 
  35.     }*/  
  36.   
  37.     // Initialize Winsock  
  38.     iResult = WSAStartup(MAKEWORD(2,2), &wsaData);  
  39.     if (iResult != 0) {  
  40.         printf("WSAStartup failed with error: %d\n", iResult);  
  41.         return 1;  
  42.     }  
  43.   
  44.     ZeroMemory( &hints, sizeof(hints) );  
  45.     hints.ai_family = AF_UNSPEC;  
  46.     hints.ai_socktype = SOCK_STREAM;  
  47.     hints.ai_protocol = IPPROTO_TCP;  
  48.   
  49.     // Resolve the server address and port  
  50.     iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);  
  51.     if ( iResult != 0 ) {  
  52.         printf("getaddrinfo failed with error: %d\n", iResult);  
  53.         WSACleanup();  
  54.         return 1;  
  55.     }  
  56.   
  57.     // Attempt to connect to an address until one succeeds  
  58.     for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {  
  59.   
  60.         // Create a SOCKET for connecting to server  
  61.         ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,  
  62.             ptr->ai_protocol);  
  63.         if (ConnectSocket == INVALID_SOCKET) {  
  64.             printf("socket failed with error: %ld\n", WSAGetLastError());  
  65.             WSACleanup();  
  66.             return 1;  
  67.         }  
  68.   
  69.         // Connect to server.  
  70.         iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);  
  71.         if (iResult == SOCKET_ERROR) {  
  72.             closesocket(ConnectSocket);  
  73.             ConnectSocket = INVALID_SOCKET;  
  74.             continue;  
  75.         }  
  76.         break;  
  77.     }  
  78.   
  79.     freeaddrinfo(result);  
  80.   
  81.     if (ConnectSocket == INVALID_SOCKET) {  
  82.         printf("Unable to connect to server!\n");  
  83.         WSACleanup();  
  84.         return 1;  
  85.     }  
  86.   
  87.     // Send an initial buffer  
  88.     iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );  
  89.     if (iResult == SOCKET_ERROR) {  
  90.         printf("send failed with error: %d\n", WSAGetLastError());  
  91.         closesocket(ConnectSocket);  
  92.         WSACleanup();  
  93.         return 1;  
  94.     }  
  95.   
  96.     printf("Bytes Sent: %ld\n", iResult);  
  97.   
  98.     // shutdown the connection since no more data will be sent  
  99.     iResult = shutdown(ConnectSocket, SD_SEND);  
  100.     if (iResult == SOCKET_ERROR) {  
  101.         printf("shutdown failed with error: %d\n", WSAGetLastError());  
  102.         closesocket(ConnectSocket);  
  103.         WSACleanup();  
  104.         return 1;  
  105.     }  
  106.   
  107.     // Receive until the peer closes the connection  
  108.     do {  
  109.   
  110.         iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);  
  111.         if ( iResult > 0 )  
  112.             printf("Bytes received: %d\n", iResult);  
  113.         else if ( iResult == 0 )  
  114.             printf("Connection closed\n");  
  115.         else  
  116.             printf("recv failed with error: %d\n", WSAGetLastError());  
  117.   
  118.     } while( iResult > 0 );  
  119.   
  120.     // cleanup  
  121.     closesocket(ConnectSocket);  
  122.     WSACleanup();  
  123.     system("pause");  
  124.     return 0;  
  125. }  

完整服务器代码

[cpp]  view plain  copy
  1. #undef UNICODE  
  2.   
  3. #define WIN32_LEAN_AND_MEAN  
  4.   
  5. #include <windows.h>  
  6. #include <winsock2.h>  
  7. #include <ws2tcpip.h>  
  8. #include <stdlib.h>  
  9. #include <stdio.h>  
  10.   
  11. // Need to link with Ws2_32.lib  
  12. #pragma comment (lib, "Ws2_32.lib")  
  13. // #pragma comment (lib, "Mswsock.lib")  
  14.   
  15. #define DEFAULT_BUFLEN 512  
  16. #define DEFAULT_PORT "27015"  
  17.   
  18. int __cdecl main(void)  
  19. {  
  20.     WSADATA wsaData;  
  21.     int iResult;  
  22.   
  23.     SOCKET ListenSocket = INVALID_SOCKET;  
  24.     SOCKET ClientSocket = INVALID_SOCKET;  
  25.   
  26.     struct addrinfo *result = NULL;  
  27.     struct addrinfo hints;  
  28.   
  29.     int iSendResult;  
  30.     char recvbuf[DEFAULT_BUFLEN];  
  31.     int recvbuflen = DEFAULT_BUFLEN;  
  32.      
  33.     // Initialize Winsock  
  34.     iResult = WSAStartup(MAKEWORD(2,2), &wsaData);  
  35.     if (iResult != 0) {  
  36.         printf("WSAStartup failed with error: %d\n", iResult);  
  37.         return 1;  
  38.     }  
  39.   
  40.     ZeroMemory(&hints, sizeof(hints));  
  41.     hints.ai_family = AF_INET;  
  42.     hints.ai_socktype = SOCK_STREAM;  
  43.     hints.ai_protocol = IPPROTO_TCP;  
  44.     hints.ai_flags = AI_PASSIVE;  
  45.   
  46.     // Resolve the server address and port  
  47.     iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);  
  48.     if ( iResult != 0 ) {  
  49.         printf("getaddrinfo failed with error: %d\n", iResult);  
  50.         WSACleanup();  
  51.         return 1;  
  52.     }  
  53.   
  54.     // Create a SOCKET for connecting to server  
  55.     ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);  
  56.     if (ListenSocket == INVALID_SOCKET) {  
  57.         printf("socket failed with error: %ld\n", WSAGetLastError());  
  58.         freeaddrinfo(result);  
  59.         WSACleanup();  
  60.         return 1;  
  61.     }  
  62.   
  63.     // Setup the TCP listening socket  
  64.     iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);  
  65.     if (iResult == SOCKET_ERROR) {  
  66.         printf("bind failed with error: %d\n", WSAGetLastError());  
  67.         freeaddrinfo(result);  
  68.         closesocket(ListenSocket);  
  69.         WSACleanup();  
  70.         return 1;  
  71.     }  
  72.   
  73.     freeaddrinfo(result);  
  74.   
  75.     iResult = listen(ListenSocket, SOMAXCONN);  
  76.     if (iResult == SOCKET_ERROR) {  
  77.         printf("listen failed with error: %d\n", WSAGetLastError());  
  78.         closesocket(ListenSocket);  
  79.         WSACleanup();  
  80.         return 1;  
  81.     }  
  82.   
  83.     // Accept a client socket  
  84.     ClientSocket = accept(ListenSocket, NULL, NULL);  
  85.     if (ClientSocket == INVALID_SOCKET) {  
  86.         printf("accept failed with error: %d\n", WSAGetLastError());  
  87.         closesocket(ListenSocket);  
  88.         WSACleanup();  
  89.         return 1;  
  90.     }  
  91.   
  92.     // No longer need server socket  
  93.     closesocket(ListenSocket);  
  94.   
  95.     // Receive until the peer shuts down the connection  
  96.     do {  
  97.   
  98.         iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);  
  99.         if (iResult > 0) {  
  100.             printf("Bytes received: %d\n", iResult);  
  101.   
  102.         // Echo the buffer back to the sender  
  103.             iSendResult = send( ClientSocket, recvbuf, iResult, 0 );  
  104.             if (iSendResult == SOCKET_ERROR) {  
  105.                 printf("send failed with error: %d\n", WSAGetLastError());  
  106.                 closesocket(ClientSocket);  
  107.                 WSACleanup();  
  108.                 return 1;  
  109.             }  
  110.             printf("Bytes sent: %d\n", iSendResult);  
  111.         }  
  112.         else if (iResult == 0)  
  113.             printf("Connection closing...\n");  
  114.         else  {  
  115.             printf("recv failed with error: %d\n", WSAGetLastError());  
  116.             closesocket(ClientSocket);  
  117.             WSACleanup();  
  118.             return 1;  
  119.         }  
  120.   
  121.     } while (iResult > 0);  
  122.   
  123.     // shutdown the connection since we're done  
  124.     iResult = shutdown(ClientSocket, SD_SEND);  
  125.     if (iResult == SOCKET_ERROR) {  
  126.         printf("shutdown failed with error: %d\n", WSAGetLastError());  
  127.         closesocket(ClientSocket);  
  128.         WSACleanup();  
  129.         return 1;  
  130.     }  
  131.   
  132.     // cleanup  
  133.     closesocket(ClientSocket);  
  134.     WSACleanup();  
  135.     system("pause");    
  136.     return 0;  
  137. }  

1.客户端应用程序启动之前就应该开始服务器应用程序。
2.若要执行服务器,将完整的服务器源代码编译和运行的可执行文件。服务器应用程序侦听 TCP 端口 27015 为客户端连接。一旦一个客户端连接,服务器从客户端和回声(发送) 收到回客户端的数据接收数据。当客户端关闭了连接时,服务器客户端套接字关闭,关闭的套接字,并退出。
3.执行客户端,完整的客户端源代码编译和运行的可执行文件。客户端应用程序需要该名称的计算机或 IP 地址的计算机在运行服务器应用程序作为命令行参数执行时传递客户端。如果客户端和服务器在样本计算机上执行的可以如下启动客户端︰
     client localhost
4.客户端试图连接到服务器上的 TCP 端口 27015。一旦客户端连接,客户端向服务器发送数据和接收从服务器返回的任何数据发送。客户端关闭套接字,然后退出。

猜你喜欢

转载自blog.csdn.net/leo_888/article/details/80390074