(转载)基于UDP的多线程网络通信程序

学习 转载,文章出处 http://blog.csdn.net/my2005lb/article/details/8689504

基于UDP的多线程网络通信程序

  分享一段基于UDP的多线程网络点对点通信程序。

  文件一:CComm.h

 

 

  1. <span style="font-size:18px;">#ifndef _CCOMM_H_  
  2. #define _CCOMM_H_  
  3.   
  4. #include <string.h>  
  5. #include <stdio.h>  
  6. #include <stdlib.h>  
  7.   
  8. #include <winsock.h>  
  9. #define socklen_t   int  
  10. #pragma comment(lib, "wsock32.lib")  
  11.   
  12. class CComm  
  13. {  
  14. private:  
  15.     static void *ListenThread(void *data);  
  16.     SOCKET ListenSocket;    // 等待接收数据的socket  
  17.     sockaddr_in srv;            // 绑定地址  
  18.     sockaddr_in client;         // 发送数据过来的地址  
  19.   
  20. public:  
  21.     CComm();  
  22.     ~CComm();  
  23.   
  24.     bool SendMsg(char *Msg, int Len, char *host, short port);  
  25.     bool Listen(int PortNum);  
  26.   
  27. };  
  28.   
  29. #endif  // #define _CCOMM_H_</span>  

 

文件一:CComm.cpp

 

  1. <span xmlns="http://www.w3.org/1999/xhtml" style="">#include "CComm.h"  
  2.   
  3.   
  4. CComm::CComm()  
  5. {  
  6.     //构造函数  
  7.     ListenSocket = INVALID_SOCKET;  // 开始设置为INVALID_SOCKET  
  8.       
  9.     #ifdef _WIN32   // 如果是win32系统  
  10.         WORD VersionRequested = MAKEWORD(1,1);  
  11.         WSADATA wsaData;  
  12.           
  13.         WSAStartup(VersionRequested, &wsaData); // 启动winsock服务  
  14.         if ( wsaData.wVersion != VersionRequested )  
  15.         {  
  16.             printf("Wrong version or WinSock not loaded\n");  
  17.             fflush(0);    
  18.         }  
  19.     #endif  
  20. }  
  21.   
  22. //析构函数  
  23. CComm::~CComm()  
  24. {  
  25.     if ( ListenSocket != INVALID_SOCKET )  
  26.         closesocket( ListenSocket );    // 如果已经创建、则关闭  
  27.   
  28.     #ifdef _WIN32   // 调用WSACleanup  
  29.         WSACleanup();  
  30.     #endif  
  31. }  
  32.   
  33. bool CComm::SendMsg( char *Msg, int Len, char *host, short port )  
  34. {  
  35.     signed int Sent;  
  36.     hostent *hostdata;  
  37.     if ( atoi(host) )   // 是否IP地址为标准形式  
  38.     {  
  39.         u_long ip = inet_addr( host );  
  40.         hostdata = gethostbyaddr( (char *)&ip, sizeof(ip), PF_INET );  
  41.     }  
  42.     else    // 否则则可能是机器名  
  43.     {  
  44.         hostdata = gethostbyname( host );  
  45.     }  
  46.   
  47.     if ( !hostdata )  
  48.     {  
  49.         printf("获得机器名错误\n");  
  50.         fflush(0);  
  51.         return false;  
  52.     }  
  53.   
  54.     sockaddr_in dest;   // 发送目标地址  
  55.     dest.sin_family = PF_INET;  
  56.     dest.sin_addr = *(in_addr *)(hostdata->h_addr_list[0]);  
  57.     dest.sin_port = htons( port );  
  58.     printf("信息已经被发送到主机 %s 端口为 %i\n", inet_ntoa(dest.sin_addr), ntohs(dest.sin_port));  
  59.     //数据发送  
  60.     Sent = sendto(ListenSocket, Msg, Len, 0, (sockaddr *)&dest, sizeof(sockaddr_in));  
  61.       
  62.     if ( Sent != Len )  
  63.     {  
  64.         printf("错误发送UDP信息\n");  
  65.         fflush(0);  
  66.         return false;  
  67.     }  
  68.       
  69.     return true;  
  70. }  
  71.   
  72. void *CComm::ListenThread( void *data )  
  73. {  
  74.     char buf[4096];  
  75.     CComm *Comm = (CComm *)data;  
  76.     int len = sizeof(Comm->client);  
  77.     while(1)    // 一直循环  
  78.     {  
  79.         //接收数据  
  80.         int result = recvfrom( Comm->ListenSocket, buf, sizeof(buf)-1, 0, (sockaddr *)&Comm->client, (socklen_t *)&len);  
  81.         if ( result > 0 )  
  82.         {  
  83.             buf[result] = 0;  
  84.             printf("Message received from host %s port %i\n", inet_ntoa(Comm->client.sin_addr), ntohs(Comm->client.sin_port));  
  85.             printf(">> %s", buf);  
  86.             fflush(0);  
  87.         }     
  88.     }     
  89. }  
  90.   
  91.   
  92. //地址绑定,注意在UDP协议中,不需要listen,这里函数listen只是绑定一个端口  
  93. bool CComm::Listen( int PortNum )  
  94. {  
  95.     ListenSocket = socket(PF_INET, SOCK_DGRAM, 0);  
  96.     if ( ListenSocket == INVALID_SOCKET )  
  97.     {  
  98.         printf("Error: socket创建失败\n");  
  99.         fflush(0);  
  100.         return false;  
  101.     }  
  102.   
  103.     srv.sin_family = PF_INET;  
  104.     srv.sin_addr.s_addr = htonl( INADDR_ANY );  // 任何地址  
  105.     srv.sin_port = htons( PortNum );  
  106.   
  107.     if ( bind( ListenSocket, (struct sockaddr *)&srv, sizeof(srv)) != 0 )  
  108.     {  
  109.         printf("Error: 绑定失败\n");  
  110.         fflush(0);  
  111.         closesocket( ListenSocket );  
  112.         return false;  
  113.     }  
  114.   
  115.     int ThreadID;   // 线程id  
  116.       
  117.         DWORD thread;  
  118.         //调用createthread创建线程  
  119.         ThreadID = (int)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)(CComm::ListenThread), (void *)this, 0, &thread);  
  120.         ThreadID = ThreadID ? 0 : 1;    // 如果成功,则返回为0  
  121.   
  122.     if(ThreadID)    // ThreadID如果不为0,则线程创建失败  
  123.     {  
  124.         printf("线程创建失败\n");  
  125.         return false;  
  126.     }  
  127.     else  
  128.         return true;  
  129. }  
  130. </span>  



 

 

 

posted @ 2013-09-01 11:12  苏苏zhao  阅读(1014)  评论(0编辑  收藏  举报