1. 程式人生 > >C++ 簡單的 Tcp 實現 socket 客戶端與客戶端通訊

C++ 簡單的 Tcp 實現 socket 客戶端與客戶端通訊

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

               

開發環境  Vs 2008  新建一個 win32 console  project

 

//  伺服器端程式碼


[cpp]
view plain copy print ?
  1. // Server.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "winsock2.h"  
  6. #pragma comment(lib, "ws2_32.lib")  
  7.   
  8. #include <iostream>  
  9. using namespace std;  
  10.   
  11. int _tmain(int argc, char* argv[])  
  12. {  
  13.     const
     int BUF_SIZE = 64;  
  14.   
  15.     WSADATA         wsd;            //WSADATA變數  
  16.     SOCKET          sServer;        //伺服器套接字  
  17.     SOCKET          sClient;        //客戶端套接字  
  18.     SOCKADDR_IN     addrServ;;      //伺服器地址  
  19.     char            buf[BUF_SIZE];  //接收資料緩衝區  
  20.     char            sendBuf[BUF_SIZE];//返回給客戶端得資料  
  21.     int             retVal;         //返回值  
  22.   
  23.     //初始化套結字動態庫  
  24.     if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)  
  25.     {  
  26.         cout << "WSAStartup failed!" << endl;  
  27.         return 1;  
  28.     }  
  29.       
  30.     //建立套接字  
  31.     sServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);      
  32.     if(INVALID_SOCKET == sServer)  
  33.     {  
  34.         cout << "socket failed!" << endl;  
  35.         WSACleanup();//釋放套接字資源;  
  36.         return  -1;  
  37.     }  
  38.       
  39.     //伺服器套接字地址   
  40.     addrServ.sin_family = AF_INET;  
  41.     addrServ.sin_port = htons(4999);  
  42.     addrServ.sin_addr.s_addr = INADDR_ANY;        
  43.     //繫結套接字  
  44.     retVal = bind(sServer, (LPSOCKADDR)&addrServ, sizeof(SOCKADDR_IN));  
  45.   
  46.     if(SOCKET_ERROR == retVal)  
  47.     {     
  48.         cout << "bind failed!" << endl;  
  49.         closesocket(sServer);   //關閉套接字  
  50.         WSACleanup();           //釋放套接字資源;  
  51.         return -1;  
  52.     }  
  53.       
  54.     //開始監聽   
  55.     retVal = listen(sServer, 1);  
  56.     if(SOCKET_ERROR == retVal)  
  57.     {  
  58.         cout << "listen failed!" << endl;         
  59.         closesocket(sServer);   //關閉套接字  
  60.         WSACleanup();           //釋放套接字資源;  
  61.         return -1;  
  62.     }  
  63.       
  64.     //接受客戶端請求  
  65.     sockaddr_in addrClient;  
  66.     int addrClientlen = sizeof(addrClient);  
  67.     sClient = accept(sServer,(sockaddr FAR*)&addrClient, &addrClientlen);  
  68.     if(INVALID_SOCKET == sClient)  
  69.     {  
  70.         cout << "accept failed!" << endl;         
  71.         closesocket(sServer);   //關閉套接字  
  72.         WSACleanup();           //釋放套接字資源;  
  73.         return -1;  
  74.     }  
  75.   
  76.       
  77.     while(true){  
  78.         //接收客戶端資料  
  79.         ZeroMemory(buf, BUF_SIZE);  
  80.         retVal = recv(sClient, buf, BUF_SIZE, 0);  
  81.         if (SOCKET_ERROR == retVal)  
  82.         {  
  83.             cout << "recv failed!" << endl;       
  84.             closesocket(sServer);   //關閉套接字  
  85.             closesocket(sClient);   //關閉套接字       
  86.             WSACleanup();           //釋放套接字資源;  
  87.             return -1;  
  88.         }  
  89.         if(buf[0] == '0')  
  90.             break;  
  91.         cout << "客戶端傳送的資料: " << buf <<endl;  
  92.           
  93.         cout << "向客戶端傳送資料: " ;  
  94.         cin >> sendBuf;  
  95.           
  96.         send(sClient, sendBuf, strlen(sendBuf), 0);  
  97.     }  
  98.       
  99.     //退出  
  100.     closesocket(sServer);   //關閉套接字  
  101.     closesocket(sClient);   //關閉套接字  
  102.     WSACleanup();           //釋放套接字資源;  
  103.   
  104.       
  105.     return 0;  
  106. }  
// Server.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "winsock2.h"#pragma comment(lib, "ws2_32.lib")#include <iostream>using namespace std;int _tmain(int argc, char* argv[]){ const int BUF_SIZE = 64; WSADATA   wsd;   //WSADATA變數 SOCKET   sServer;  //伺服器套接字 SOCKET   sClient;  //客戶端套接字 SOCKADDR_IN  addrServ;;  //伺服器地址 char   buf[BUF_SIZE]; //接收資料緩衝區 char   sendBuf[BUF_SIZE];//返回給客戶端得資料 int    retVal;   //返回值 //初始化套結字動態庫 if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) {  cout << "WSAStartup failed!" << endl;  return 1; }  //建立套接字 sServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  if(INVALID_SOCKET == sServer) {  cout << "socket failed!" << endl;  WSACleanup();//釋放套接字資源;  return  -1; }  //伺服器套接字地址  addrServ.sin_family = AF_INET; addrServ.sin_port = htons(4999); addrServ.sin_addr.s_addr = INADDR_ANY;   //繫結套接字 retVal = bind(sServer, (LPSOCKADDR)&addrServ, sizeof(SOCKADDR_IN)); if(SOCKET_ERROR == retVal) {   cout << "bind failed!" << endl;  closesocket(sServer); //關閉套接字  WSACleanup();   //釋放套接字資源;  return -1; }  //開始監聽  retVal = listen(sServer, 1); if(SOCKET_ERROR == retVal) {  cout << "listen failed!" << endl;    closesocket(sServer); //關閉套接字  WSACleanup();   //釋放套接字資源;  return -1; }  //接受客戶端請求 sockaddr_in addrClient; int addrClientlen = sizeof(addrClient); sClient = accept(sServer,(sockaddr FAR*)&addrClient, &addrClientlen); if(INVALID_SOCKET == sClient) {  cout << "accept failed!" << endl;    closesocket(sServer); //關閉套接字  WSACleanup();   //釋放套接字資源;  return -1; }  while(true){  //接收客戶端資料  ZeroMemory(buf, BUF_SIZE);  retVal = recv(sClient, buf, BUF_SIZE, 0);  if (SOCKET_ERROR == retVal)  {   cout << "recv failed!" << endl;     closesocket(sServer); //關閉套接字   closesocket(sClient); //關閉套接字     WSACleanup();   //釋放套接字資源;   return -1;  }  if(buf[0] == '0')   break;  cout << "客戶端傳送的資料: " << buf <<endl;    cout << "向客戶端傳送資料: " ;  cin >> sendBuf;    send(sClient, sendBuf, strlen(sendBuf), 0); }  //退出 closesocket(sServer); //關閉套接字 closesocket(sClient); //關閉套接字 WSACleanup();   //釋放套接字資源;  return 0;}

 

//  客戶端程式碼

 

[cpp] view plain copy print ?
  1. // Client.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "winsock2.h"  
  6. #include <iostream>  
  7. #pragma comment(lib, "ws2_32.lib")  
  8.   
  9. using namespace std;  
  10. BOOL    RecvLine(SOCKET s, char* buf);  //讀取一行資料  
  11.   
  12. int main(int argc, char* argv[])  
  13. {  
  14.     const int BUF_SIZE = 64;  
  15.   
  16.     WSADATA         wsd;            //WSADATA變數  
  17.     SOCKET          sHost;          //伺服器套接字  
  18.     SOCKADDR_IN     servAddr;       //伺服器地址  
  19.     char            buf[BUF_SIZE];  //接收資料緩衝區  
  20.     char            bufRecv[BUF_SIZE];  
  21.     int             retVal;         //返回值  
  22.       
  23.     //初始化套結字動態庫  
  24.     if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)  
  25.     {  
  26.         cout << "WSAStartup failed!" << endl;  
  27.         return -1;  
  28.     }  
  29.       
  30.     //建立套接字  
  31.     sHost = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    
  32.     if(INVALID_SOCKET == sHost)  
  33.     {  
  34.         cout << "socket failed!" << endl;  
  35.         WSACleanup();//釋放套接字資源  
  36.         return  -1;  
  37.     }  
  38.   
  39.     //設定伺服器地址  
  40.     servAddr.sin_family =AF_INET;  
  41.     servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");  
  42.     servAddr.sin_port = htons((short)4999);  
  43.     int nServAddlen  = sizeof(servAddr);  
  44.   
  45.     //連線伺服器  
  46.     retVal=connect(sHost,(LPSOCKADDR)&servAddr, sizeof(servAddr));    
  47.     if(SOCKET_ERROR == retVal)  
  48.     {  
  49.         cout << "connect failed!" << endl;    
  50.         closesocket(sHost); //關閉套接字  
  51.         WSACleanup();       //釋放套接字資源  
  52.         return -1;  
  53.     }  
  54.     while(true){  
  55.         //向伺服器傳送資料  
  56.         ZeroMemory(buf, BUF_SIZE);  
  57.         cout << " 向伺服器傳送資料:  ";  
  58.         cin >> buf;  
  59.         retVal = send(sHost, buf, strlen(buf), 0);  
  60.         if (SOCKET_ERROR == retVal)  
  61.         {  
  62.             cout << "send failed!" << endl;  
  63.             closesocket(sHost); //關閉套接字  
  64.             WSACleanup();       //釋放套接字資源  
  65.             return -1;  
  66.         }  
  67.         //RecvLine(sHost, bufRecv);  
  68.         recv(sHost, bufRecv,5 , 0);     // 接收伺服器端的資料, 只接收5個字元  
  69.         cout << endl <<"從伺服器接收資料:" << bufRecv;  
  70.   
  71.     }  
  72.     //退出  
  73.     closesocket(sHost); //關閉套接字  
  74.     WSACleanup();       //釋放套接字資源  
  75.     return 0;  
  76. }  
// Client.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "winsock2.h"#include <iostream>#pragma comment(lib, "ws2_32.lib")using namespace std;BOOL RecvLine(SOCKET s, char* buf); //讀取一行資料int main(int argc, char* argv[]){ const int BUF_SIZE = 64; WSADATA   wsd;   //WSADATA變數 SOCKET   sHost;   //伺服器套接字 SOCKADDR_IN  servAddr;  //伺服器地址 char   buf[BUF_SIZE]; //接收資料緩衝區 char   bufRecv[BUF_SIZE]; int    retVal;   //返回值  //初始化套結字動態庫 if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) {  cout << "WSAStartup failed!" << endl;  return -1; }  //建立套接字 sHost = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  if(INVALID_SOCKET == sHost) {  cout << "socket failed!" << endl;  WSACleanup();//釋放套接字資源  return  -1; } //設定伺服器地址 servAddr.sin_family =AF_INET; servAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servAddr.sin_port = htons((short)4999); int nServAddlen  = sizeof(servAddr); //連線伺服器 retVal=connect(sHost,(LPSOCKADDR)&servAddr, sizeof(servAddr));  if(SOCKET_ERROR == retVal) {  cout << "connect failed!" << endl;   closesocket(sHost); //關閉套接字  WSACleanup();  //釋放套接字資源  return -1; } while(true){  //向伺服器傳送資料  ZeroMemory(buf, BUF_SIZE);  cout << " 向伺服器傳送資料:  ";  cin >> buf;  retVal = send(sHost, buf, strlen(buf), 0);  if (SOCKET_ERROR == retVal)  {   cout << "send failed!" << endl;   closesocket(sHost); //關閉套接字   WSACleanup();  //釋放套接字資源   return -1;  }  //RecvLine(sHost, bufRecv);  recv(sHost, bufRecv,5 , 0);  // 接收伺服器端的資料, 只接收5個字元  cout << endl <<"從伺服器接收資料:" << bufRecv; } //退出 closesocket(sHost); //關閉套接字 WSACleanup();  //釋放套接字資源 return 0;}

 

 

 

 

 

 

 

           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述