BroadCast.cpp
资源名称:视频会议系统.rar [点击查看]
上传用户:popouu88
上传日期:2013-02-11
资源大小:2894k
文件大小:2k
源码类别:
IP电话/视频会议
开发平台:
Visual C++
- // BroadCast.cpp: implementation of the CBroadCast class.
- //
- //////////////////////////////////////////////////////////////////////
- #include "stdafx.h"
- #include "BroadCast.h"
- #ifdef _DEBUG
- #undef THIS_FILE
- static char THIS_FILE[]=__FILE__;
- #define new DEBUG_NEW
- #endif
- #pragma comment( lib , "ws2_32.lib")
- //////////////////////////////////////////////////////////////////////
- // Construction/Destruction
- //////////////////////////////////////////////////////////////////////
- int CBroadCast::InitWSAStatup = 0;
- CBroadCast::CBroadCast()
- {
- this->sbroadcast = INVALID_SOCKET;
- this->nPort = 0;
- memset( &this->buffer , 0 , sizeof( this->buffer ) );
- if( ! CBroadCast::InitWSAStatup )
- {
- WSADATA data;
- ::WSAStartup( MAKEWORD( 2 , 2 ) , &data );
- }
- CBroadCast::InitWSAStatup ++;
- }
- CBroadCast::~CBroadCast()
- {
- CBroadCast::InitWSAStatup --;
- if( ! CBroadCast::InitWSAStatup )
- ::WSACleanup( );
- }
- int CBroadCast::Create( const int nPort )
- {
- this->sbroadcast = ::socket( AF_INET, SOCK_DGRAM, 0 );
- if( this->sbroadcast == INVALID_SOCKET )
- return 0;
- BOOL fBroadcast = TRUE;
- if( setsockopt( this->sbroadcast , SOL_SOCKET , SO_BROADCAST , ( char * )&fBroadcast , sizeof( BOOL ) ) == SOCKET_ERROR )
- {
- return 0;
- }
- sockaddr_in addr;
- addr.sin_addr.s_addr = INADDR_ANY;
- addr.sin_family = AF_INET;
- addr.sin_port = ::htons( nPort );
- if( bind( this->sbroadcast , ( SOCKADDR * )&addr , sizeof( addr ) ) == SOCKET_ERROR )
- {
- return 0;
- }
- int len = sizeof( addr );
- ::getsockname( this->sbroadcast , ( SOCKADDR * )&addr , &len );
- this->nPort = ! nPort ? ntohs( addr.sin_port ): nPort;
- return this->nPort;
- }
- char * CBroadCast::Receive( int &size )
- {
- sockaddr_in addr;
- int len = sizeof( addr );
- size = ::recvfrom( this->sbroadcast , this->buffer , sizeof( this->buffer ) , 0 , ( SOCKADDR * )&addr , &len );
- if( size <= 0 )
- return NULL;
- return this->buffer;
- }
- bool CBroadCast::Send( const char * buffer , const int size )
- {
- sockaddr_in addr;
- addr.sin_addr.s_addr = ::inet_addr( "255.255.255.255" );
- addr.sin_family = AF_INET;
- addr.sin_port = ::htons( this->nPort );
- int len = sizeof( addr );
- return ::sendto( this->sbroadcast , buffer , size , 0 , ( SOCKADDR * )&addr , len ) >= size;
- }