예제 #1
0
파일: netlib.cpp 프로젝트: hgl888/TeamTalk
bool netlib_shutdown(net_handle_t handle)
{
	CBaseSocket* pSocket = FindBaseSocket(handle);
	if (!pSocket)
		return false;

	return pSocket->Shutdown(2);
}
예제 #2
0
파일: netlib.cpp 프로젝트: narychen/egserv
int netlib_recv(net_handle_t handle, void* buf, int len)
{
	CBaseSocket* pSocket = FindBaseSocket(handle);
	if (!pSocket)
		return NETLIB_ERROR;

	int ret = pSocket->Recv(buf, len);
	pSocket->ReleaseRef();
	return ret;
}
예제 #3
0
파일: netlib.cpp 프로젝트: narychen/egserv
int netlib_close(net_handle_t handle)
{
	CBaseSocket* pSocket = FindBaseSocket(handle);
	if (!pSocket)
		return NETLIB_ERROR;

	int ret = pSocket->Close();
	pSocket->ReleaseRef();
	return ret;
}
예제 #4
0
파일: netlib.cpp 프로젝트: hgl888/Server
int netlib_send( net_handle_t handle, void *buf, int len)
{
    CBaseSocket *pSocket = FindBaseSocket(handle);
    if( NULL == pSocket)
    {
        return NETLIB_ERROR;
    }
    int ret = pSocket->Send(buf, len);
    pSocket->ReleaseRef();
    return ret;
}
예제 #5
0
CBaseSocket* FindBaseSocket(net_handle_t fd)
{
    CBaseSocket* pSocket = NULL;
    SocketMap::iterator iter = g_socket_map.find(fd);
    if (iter != g_socket_map.end())
    {
        pSocket = iter->second;
        pSocket->AddRef();
    }
    
    return pSocket;
}
예제 #6
0
파일: netlib.cpp 프로젝트: hgl888/TeamTalk
int netlib_close(net_handle_t handle)
{
	CBaseSocket* pSocket = FindBaseSocket(handle);
	if (!pSocket)
	{
		LOG__(APP, _T("can not find base socket,handle:%d"),handle);
		return NETLIB_ERROR;
	}

	int ret = pSocket->Close();
	pSocket->ReleaseRef();
	return ret;
}
예제 #7
0
파일: netlib.cpp 프로젝트: 9618211/TTServer
int netlib_option(net_handle_t handle, int opt, void* optval)
{
	CBaseSocket* pSocket = FindBaseSocket(handle);
	if (!pSocket)
		return NETLIB_ERROR;

	if ((opt >= NETLIB_OPT_GET_REMOTE_IP) && !optval)
		return NETLIB_ERROR;

	switch (opt)
	{
	case NETLIB_OPT_SET_CALLBACK:
		pSocket->SetCallback((callback_t)optval);
		break;
	case NETLIB_OPT_SET_CALLBACK_DATA:
		pSocket->SetCallbackData(optval);
		break;
	case NETLIB_OPT_GET_REMOTE_IP:
		*(string*)optval = pSocket->GetRemoteIP();
		break;
	case NETLIB_OPT_GET_REMOTE_PORT:
		*(uint16_t*)optval = pSocket->GetRemotePort();
		break;
	case NETLIB_OPT_GET_LOCAL_IP:
		*(string*)optval = pSocket->GetLocalIP();
		break;
	case NETLIB_OPT_GET_LOCAL_PORT:
		*(uint16_t*)optval = pSocket->GetLocalPort();
	}

	pSocket->ReleaseRef();
	return NETLIB_OK;
}
예제 #8
0
파일: netlib.cpp 프로젝트: hgl888/Server
int netlib_listen(const char *server_ip, uint16_t port,
                  callback_t callback, void *callback_data)
{
    CBaseSocket *pSocket = new CBaseSocket();
    if( NULL == pSocket )
    {
        return NETLIB_ERROR;
    }
    int ret = pSocket->Listen(server_ip, port, callback, callback_data);
    if( ret == NETLIB_ERROR){
        delete pSocket;
    }
    return ret;
}
예제 #9
0
파일: netlib.cpp 프로젝트: narychen/egserv
net_handle_t netlib_connect(
		const char* server_ip, 
		uint16_t	port, 
		callback_t	callback, 
		void*		callback_data)
{
	CBaseSocket* pSocket = new CBaseSocket();
	if (!pSocket)
		return NETLIB_INVALID_HANDLE;

	net_handle_t handle = pSocket->Connect(server_ip, port, callback, callback_data);
	if (handle == NETLIB_INVALID_HANDLE)
		delete pSocket;
	return handle;
}
예제 #10
0
void CBaseSocket::_AcceptNewSocket()
{
    SOCKET fd = 0;
    sockaddr_in peer_addr;
    socklen_t addr_len = sizeof(sockaddr_in);
    char ip_str[64];
    
    while ( (fd = accept(m_socket, (sockaddr*)&peer_addr, &addr_len)) != INVALID_SOCKET )
    {
        CBaseSocket* pSocket = new CBaseSocket();
        
        uint32_t ip = ntohl(peer_addr.sin_addr.s_addr);
        uint16_t port = ntohs(peer_addr.sin_port);
        
        snprintf(ip_str, sizeof(ip_str), "%d.%d.%d.%d", ip >> 24, (ip >> 16) & 0xFF, (ip >> 8) & 0xFF, ip & 0xFF);
        
//        log("AcceptNewSocket, socket=%d from %s:%d\n", fd, ip_str, port);
        
        pSocket->SetSocket(fd);
        pSocket->SetCallback(m_callback);
        pSocket->SetCallbackData(m_callback_data);
        pSocket->SetState(SOCKET_STATE_CONNECTED);
        pSocket->SetRemoteIP(ip_str);
        pSocket->SetRemotePort(port);
        
        _SetNoDelay(fd);
        _SetNonblock(fd);
        AddBaseSocket(pSocket);
        CEventDispatch::Instance()->AddEvent(fd, SOCKET_READ | SOCKET_EXCEP);
        m_callback(m_callback_data, NETLIB_MSG_CONNECT, (net_handle_t)fd, NULL);
    }
}
예제 #11
0
파일: netImpl.cpp 프로젝트: Felard/MoSync
void Syscall::ConnOp::addSockConnect(CBaseSocket& sock, TSockAddr& addr, int port,
	const TDesC* hostname)
{
	CSO_ADD(SockConnect, addr, port, sock);
	CMySecureSocket* mss = sock.ssl();
	if(mss) {
		CSO_ADD(SecureHandshake, *mss, hostname);
	}
}
예제 #12
0
파일: netlib.cpp 프로젝트: hgl888/Server
int netlib_option( net_handle_t handel, int opt, void *optval)
{
    CBaseSocket *pSocket = FindBaseSocket(handel);
    if( NULL == pSocket )
    {
        return NETLIB_ERROR;
    }
    
    if((opt >= NETLIB_OPT_GET_REMOTE_IP) && !optval )
    {
        return NETLIB_ERROR;
    }
    
    switch (opt) {
        case NETLIB_OPT_SET_CALLBACK:
            pSocket->SetCallback((callback_t)optval);
            break;
        case NETLIB_OPT_SET_CALLBACK_DATA:
            pSocket->SetCallbackData(optval);
            break;
        case NETLIB_OPT_GET_REMOTE_IP:
            *(string*)optval = pSocket->GetRemoteIP();
            break;
        case NETLIB_OPT_GET_REMOTE_PORT:
            *(string*)optval = pSocket->GetRemotePort();
            break;
        case NETLIB_OPT_GET_LOCAL_IP:
            *(string*)optval = pSocket->GetLocalIP();
            break;
        case NETLIB_OPT_GET_LOCAL_PORT:
            *(string*)optval = pSocket->GetLocalPort();
            break;
        case NETLIB_OPT_SET_SEND_BUF_SIZE:
            pSocket->SetSendBufSize(*(uint32_t*)optval);
            break;
        case NETLIB_OPT_SET_RECV_BUF_SIZE:
            pSocket->SetRecvBufSize(*(uint32_t*)optval);
            break;
    }
    pSocket->ReleaseRef();
    return NETLIB_OK;
}
예제 #13
0
void CBaseSocket::_AcceptNewSocket()
{
	SOCKET fd = 0;
	sockaddr_in peer_addr;
	socklen_t addr_len = sizeof(sockaddr_in);
	char ip_str[64];
	while ( (fd = accept(m_socket, (sockaddr*)&peer_addr, &addr_len)) != INVALID_SOCKET )
	{
		CBaseSocket* pSocket = new CBaseSocket(m_pBaseServer);
		uint32_t ip = ntohl(peer_addr.sin_addr.s_addr);
		uint16_t port = ntohs(peer_addr.sin_port);

		snprintf(ip_str, sizeof(ip_str), "%d.%d.%d.%d", ip >> 24, (ip >> 16) & 0xFF, (ip >> 8) & 0xFF, ip & 0xFF);

		printf("AcceptNewSocket, socket=%d from %s:%d\n", fd, ip_str, port);

		pSocket->SetSocket(fd);
		pSocket->SetState(SOCKET_STATE_CONNECTED);
		pSocket->SetRemoteIP(ip_str);
		pSocket->SetRemotePort(port);
		pSocket->SetNotify(m_Notify);

		_SetNoDelay(fd);
		_SetNonblock(fd);
		m_pBaseServer->AddBaseSocket(pSocket);
		m_pBaseServer->AddEvent(fd, SOCKET_READ | SOCKET_EXCEP);
		m_Notify->OnConnect((net_handle_t)fd);
	}
}
예제 #14
0
void CEventDispatch::StartDispatch(uint32_t wait_timeout)
{
	struct epoll_event events[1024];
	int nfds = 0;
    
	while (running)
	{
		nfds = epoll_wait(m_epfd, events, 1024, wait_timeout);
		for (int i = 0; i < nfds; i++)
		{
			int ev_fd = events[i].data.fd;
			CBaseSocket* pSocket = FindBaseSocket(ev_fd);
			if (!pSocket)
				continue;

			if (events[i].events & EPOLLIN)
			{
				//LOG__(NET,  "OnRead, socket=%d\n", ev_fd);
				pSocket->OnRead();
			}

			if (events[i].events & EPOLLOUT)
			{
				//LOG__(NET,  "OnWrite, socket=%d\n", ev_fd);
				pSocket->OnWrite();
			}

			if (events[i].events & (EPOLLPRI | EPOLLERR | EPOLLHUP))
			{
				//LOG__(NET,  "OnClose, socket=%d\n", ev_fd);
				pSocket->OnClose();
			}

			pSocket->ReleaseRef();
		}

		_CheckTimer();
		_CheckLoop();
	}
}
예제 #15
0
void CEventDispatch::StartDispatch()
{
    struct epoll_event events[1024];
    int nfds = 0;

    while (true)
    {
        nfds = epoll_wait(m_epfd, events, 1024, MIN_TIMER_DURATION);
        for (int i = 0; i < nfds; i++)
        {
            int ev_fd = events[i].data.fd;
            CBaseSocket* pSocket = FindBaseSocket(ev_fd);
            if (!pSocket)
                continue;

            if (events[i].events & EPOLLIN)
            {
                //log("OnRead, socket=%d\n", ev_fd);
                pSocket->OnRead();
            }

            if (events[i].events & EPOLLOUT)
            {
                //log("OnWrite, socket=%d\n", ev_fd);
                pSocket->OnWrite();
            }

            if (events[i].events & (EPOLLPRI | EPOLLERR | EPOLLHUP))
            {
                //log("OnClose, socket=%d\n", ev_fd);
                pSocket->OnClose();
            }

            pSocket->ReleaseRef();
        }

        _CheckTimer();
    }
}
예제 #16
0
void CEventDispatch::StartDispatch()
{
    struct kevent events[1024];
    int nfds = 0;
    struct timespec timeout;

    timeout.tv_sec = 0;
    timeout.tv_nsec = MIN_TIMER_DURATION * 1000000;

    while (true)
    {
        nfds = kevent(m_kqfd, NULL, 0, events, 1024, &timeout);

        for (int i = 0; i < nfds; i++)
        {
            int ev_fd = events[i].ident;
            CBaseSocket* pSocket = FindBaseSocket(ev_fd);
            if (!pSocket)
                continue;

            if (events[i].filter == EVFILT_READ)
            {
                //log("OnRead, socket=%d\n", ev_fd);
                pSocket->OnRead();
            }

            if (events[i].filter == EVFILT_WRITE)
            {
                //log("OnWrite, socket=%d\n", ev_fd);
                pSocket->OnWrite();
            }

            pSocket->ReleaseRef();
        }

        _CheckTimer();
    }
}
예제 #17
0
void CEventDispatch::StartDispatch(uint32_t wait_timeout)
{
	struct kevent events[1024];
	int nfds = 0;
	struct timespec timeout;
	timeout.tv_sec = 0;
	timeout.tv_nsec = wait_timeout * 1000000;
    
    while (running)
	{
		nfds = kevent(m_kqfd, NULL, 0, events, 1024, &timeout);

		for (int i = 0; i < nfds; i++)
		{
			int ev_fd = events[i].ident;
			CBaseSocket* pSocket = FindBaseSocket(ev_fd);
			if (!pSocket)
				continue;

			if (events[i].filter == EVFILT_READ)
			{
				//LOG__(NET,  "OnRead, socket=%d\n", ev_fd);
				pSocket->OnRead();
			}

			if (events[i].filter == EVFILT_WRITE)
			{
				//LOG__(NET,  "OnWrite, socket=%d\n", ev_fd);
				pSocket->OnWrite();
			}

			pSocket->ReleaseRef();
		}

		_CheckTimer();
		_CheckLoop();
	}
}
예제 #18
0
int  CCommunication::CheckHeart4PhoneS1(CBaseSocket  & ttBSocket , SOCKET & sendSocket)
{
	//建立连接
	CString  strShowInfo;

	int nRet = -1;

	nRet = ttBSocket.NoNagleCreateSocket(&sendSocket);
	if(0x00 != nRet)
	{
		nRet = GetLastError();

		strShowInfo.Format(_T("[CCommunication::CheckHeart4PhoneS1] InitializeAndCreateSocket ErrorNo=[%d].\r\n"), nRet);
		XWriteEventLog(strShowInfo);

		m_nExceptionHeart++;
		ttBSocket.CloseSocket( &sendSocket);
		return -2;
	}

	nRet = ttBSocket.ConnectToServer(&sendSocket, CCommunication::m_Port, CCommunication::m_Ip);
	if(0x00 != nRet)
	{	
		Sleep(1000);
		nRet = ttBSocket.ConnectToServer(&sendSocket, CCommunication::m_Port, CCommunication::m_Ip);
		if(nRet != 0x00)
		{
			Sleep(2000);
			nRet = ttBSocket.ConnectToServer(&sendSocket, CCommunication::m_Port, CCommunication::m_Ip);
		}

		if(nRet != 0x00)
		{
			nRet = GetLastError();
			strShowInfo.Format(_T("[CCommunication::CheckHeart4PhoneS1] ConnectToServer IP=[%s] Port =[%d] ErrorNo=[%d].\r\n"), CCommunication::m_Ip,CCommunication::m_Port,nRet);
			XWriteEventLog(strShowInfo);

			m_nExceptionHeart++;
			ttBSocket.CloseSocket( &sendSocket);

			if( 10061 == nRet)
			{
				return -33;
			}
			return -3;
		}
	}
	else
	{
		strShowInfo.Format(_T("[CCommunication::CheckHeart4PhoneS1] ConnectToServer IP=[%s] Port =[%d] Connect OK\r\n"), CCommunication::m_Ip,CCommunication::m_Port);
		XWriteEventLog(strShowInfo);

	}

	//////////////////////////////////////////////////////////////////////
	return  0;

}
예제 #19
0
void CEventDispatch::StartDispatch(uint32_t wait_timeout)
{
	struct epoll_event events[1024];
	int nfds = 0;

    if(running)
        return;
    running = true;

	while (running){
		nfds = epoll_wait(m_epfd, events, 1024, wait_timeout);
		for (int i = 0; i < nfds; i++){
			int ev_fd = events[i].data.fd;
			CBaseSocket* pSocket = FindBaseSocket(ev_fd);
			if (!pSocket)
				continue;

            #ifdef EPOLLRDHUP
            if (events[i].events & EPOLLRDHUP){
            	Logger.Log(INFO, "On Peer Close, socket=%d", ev_fd);
                pSocket->OnClose();
            }
            #endif
            // Commit End

			if (events[i].events & EPOLLIN){
				Logger.Log(INFO, "OnRead, socket=%d\n", ev_fd);
				pSocket->OnRead();
			}

			if (events[i].events & EPOLLOUT){
				Logger.Log(INFO, "OnWrite, socket=%d\n", ev_fd);
				pSocket->OnWrite();
			}

			if (events[i].events & (EPOLLPRI | EPOLLERR | EPOLLHUP)){
				Logger.Log(INFO, "OnClose, socket=%d\n", ev_fd);
				pSocket->OnClose();
			}

			pSocket->ReleaseRef();
		}

		_CheckTimer();
        _CheckLoop();
	}
}
예제 #20
0
/*************************************************
  Function:      AddServerChannel 
  Description:   建立通讯通道,
  Input:  
  Output:         
  Return:         
  Note:			对于	
*************************************************/
INT CNetService::AddServerChannel(const char* pszBindIP, UINT16 unPort, 
					 enumNetProtocolType eProtocolType, ISocketChannel** pSocketChnl)
{
	CGSAutoMutex		GSAutoMutex(&m_GSMutex);

	if ( !m_bIsInit )
	{
		return ERROR_NET_UNKNOWN;
	}

	// 为了区分协议栈和gsp,得这么写
	/*if (!g_clsLogPtr)
	{
		m_clsThreadDealNetEvent.SetLogPath( GetApplicationPath().c_str() );

		m_clsThreadDealNetEvent.m_clsThreadPool.SetLogInstancePtr( m_clsThreadDealNetEvent.GetLogInstancePtr());
	}*/	


	if (true == m_clsThreadDealNetEvent.IfMaxChannelCount())
	{
		return ERROR_NET_MAX_CHANNEL_COUNT;//已达到最大连接数
	}
	
	if (unPort < 0) //绑定的IP为null时 表示绑定本机任意IP
	{
		return ERROR_NET_PARAM_WRONG;
	}

	//建立socketchannel
	CSocketChannel *pclsSocketChnl = new CSocketChannel();//此指针保存到队列中,直到通道需要删除时才释放.在~CNetInterfaceCommData(void)里释放
	
	if ( NULL == pclsSocketChnl )
	{
		return ERROR_NET_UNKNOWN;
	}
	
	//设置通道属性
	pclsSocketChnl->SetLocalIPPort(pszBindIP, unPort);
	pclsSocketChnl->SetServerType( SERVER );
	pclsSocketChnl->SetNetProtocolType( eProtocolType );
	pclsSocketChnl->SetChannelType( LISTEN_CHANNEL );//不管是UDP还是tcp 凡是AddServerChannel add的通道都认为是监听通道

	
	//建立basesocket
	CBaseSocket* pBaseSocket = NULL;//生命周期和pclsSocketChnl一样,
#if _WIN32
	if (eProtocolType == NET_PROTOCOL_TCP)
	{
		pBaseSocket = new CWinTcpSocket();
		
	}
	else
	{
		pBaseSocket = new CWinUdpSocket();
	}
#endif
#if _LINUX
	if (eProtocolType == NET_PROTOCOL_TCP)
	{
		pBaseSocket = new CLinuxTcpSocket();
	}
	else
	{
		pBaseSocket = new CLinuxUdpSocket();

	}
#endif

	if ( NULL == pBaseSocket )
	{
		if ( pclsSocketChnl )
		{
			pclsSocketChnl->CloseChannel();
			delete pclsSocketChnl;
			pclsSocketChnl = NULL;
		}
		return ERROR_NET_UNKNOWN;
	}
	 
	pBaseSocket->SetBlockMode( m_clsThreadDealNetEvent.GetBlockMode() );
	m_clsServerChannel.SetLocalIPPort(pszBindIP, unPort);
	//创建通道
	if (m_clsServerChannel.CreateChannel(pBaseSocket) != ERROR_BASE_SUCCESS)
	{
		//创建 通道失败
		pclsSocketChnl->CloseChannel();
		delete pclsSocketChnl;
		pclsSocketChnl = NULL;

		delete pBaseSocket;
		pBaseSocket = NULL;

		return ERROR_NET_CREATE_CHANNEL_FAIL;
	}


	//保存CBaseSocket
	pclsSocketChnl->SetCbaseSocketPoint(pBaseSocket);

	//将socketchannel存入vector容器
    m_clsThreadDealNetEvent.SaveSocketChannel(pclsSocketChnl);

	pclsSocketChnl->SetLogInstancePtr(m_clsThreadDealNetEvent.GetLogInstancePtr());

#if OPERATING_SYSTEM

	if (eProtocolType == NET_PROTOCOL_TCP)
	{
		pstruThreadPoolTask	 pTask = (pstruThreadPoolTask) malloc(sizeof(struThreadTask));//在任务结束时或程序退出时的在线程池的Uninitialize()中释放

		if ( NULL == pTask )
		{
			return ERROR_NET_UNKNOWN;
		}

		memset(pTask,0x0,sizeof(struThreadTask));
		pTask->pFunction = &CCommunicationManager::Listen;
		pTask->enumEvent = LISTEN;
		pTask->pObject = (CCommunicationManager*)&m_clsThreadDealNetEvent;
		pTask->pObject2 = pclsSocketChnl;
		m_clsThreadDealNetEvent.m_clsThreadPool.AssignTask(pTask);
		m_clsThreadDealNetEvent.m_clsThreadPool.WakeUpThread();

	}
	

#elif _WIN32
	
	if (eProtocolType == NET_PROTOCOL_UDP)
	{
		//加入完成端口
		m_clsThreadDealNetEvent.AddToIoCompletionPort((HANDLE)pBaseSocket->GetSocket(), (DWORD)pclsSocketChnl->GetIOCPHandleData());
		//发起接收
		pclsSocketChnl->RecvData();
	}
	else
	{
		//m_clsThreadDealNetEvent.m_clsThreadPool.AddThread(1);//增加一个线程去完成下面创建的任务,即监听

		pstruThreadPoolTask	 pTask = (pstruThreadPoolTask) malloc(sizeof(struThreadTask));//在任务结束时或程序退出时的在线程池的Uninitialize()中释放

		if ( NULL == pTask )
		{
			return ERROR_NET_UNKNOWN;
		}

		memset(pTask,0x0,sizeof(struThreadTask));
		pTask->pFunction = &CCommunicationManager::Listen;
		pTask->enumEvent = LISTEN;
		pTask->pObject = (CCommunicationManager*)&m_clsThreadDealNetEvent;
		pTask->pObject2 = pclsSocketChnl;
		m_clsThreadDealNetEvent.m_clsThreadPool.AssignTask(pTask);
		m_clsThreadDealNetEvent.m_clsThreadPool.WakeUpThread();
	}
	

#else	//linux
	
	if (eProtocolType == NET_PROTOCOL_UDP)
	{
		//加入EPOLL
		m_clsThreadDealNetEvent.EpollCtrl( EPOLL_CTL_ADD,pBaseSocket->GetSocket(),pclsSocketChnl->GetEpollEvent());

	}
	else
	{

		pstruThreadPoolTask	 pTask = (pstruThreadPoolTask) malloc(sizeof(struThreadTask));//在任务结束时或程序退出时的在线程池的Uninitialize()中释放

		if ( NULL == pTask )
		{
			return ERROR_NET_UNKNOWN;
		}

		memset(pTask,0x0,sizeof(struThreadTask));
		pTask->pFunction = &CCommunicationManager::Listen;
		pTask->enumEvent = LISTEN;
		pTask->pObject = (CCommunicationManager*)&m_clsThreadDealNetEvent;
		pTask->pObject2 = pclsSocketChnl;
		m_clsThreadDealNetEvent.m_clsThreadPool.AssignTask(pTask);
	}
#endif

	//转换
	*pSocketChnl = (ISocketChannel*)pclsSocketChnl;

	return ERROR_BASE_SUCCESS;
}
예제 #21
0
/********************************************************************************
  Function:		AddClientChannel
  Description:	增加一个客户端
  Input:  		pszhost 主机地址	unDesPort 目的端口	pszBindIP 本地IP地址 可以是0 表示本机的任意IP	localport 本地端口 可以为0 系统自动分配
  Output:		pSocketChnl   成功返回通道指针 
  Return:  		       
  Note:					
  Author:        	CHC
  Date:				2010/08/31
********************************************************************************/
INT CNetService::AddClientChannel( const char *pszhost, UINT16 unDesPort,const char *pszBindIP, 
									UINT16 localport,enumNetProtocolType eProtocolType,  ISocketChannel** pSocketChnl)
{
	if ( m_bIsExit )
	{
		return ERROR_NET_UNKNOWN;
	}

	if ( !m_bIsInit )
	{
		return ERROR_NET_UNKNOWN;
	}

	CGSAutoMutex		GSAutoMutex(&m_GSMutex);

	// 为了区分协议栈和gsp,得这么写
	/*if (!g_clsLogPtr)
	{
	m_clsThreadDealNetEvent.SetLogPath( GetApplicationPath().c_str() );

	m_clsThreadDealNetEvent.m_clsThreadPool.SetLogInstancePtr( m_clsThreadDealNetEvent.GetLogInstancePtr());
	}*/

	if (true == m_clsThreadDealNetEvent.IfMaxChannelCount())
	{
		return ERROR_NET_MAX_CHANNEL_COUNT;//已达到最大连接数
	}

	if (pszhost == NULL)		
	{
		return ERROR_NET_PARAM_WRONG;
	}

	//建立socketchannel
	CSocketChannel *pclsSocketChnl = new CSocketChannel();//此指针保存到队列中,直到通道需要删除时才释放,比如程序退出,或者上层请求关闭通道
	if ( NULL == pclsSocketChnl )
	{
		// 没申请到内存
		return ERROR_NET_UNKNOWN;
	}
	pclsSocketChnl->SetLocalIPPort(pszBindIP, localport);
	pclsSocketChnl->SetReMoteIPPort(pszhost, unDesPort);
	pclsSocketChnl->SetNetProtocolType( eProtocolType );
	pclsSocketChnl->SetServerType( CLIENT );
	pclsSocketChnl->SetChannelType( COMM_CHANNEL );//客户端建立的都是通讯通道

	//建立basesocket
	CBaseSocket* pBaseSocket = NULL;//生命周期和pclsSocketChnl一样,
#if _WIN32
	if (eProtocolType == NET_PROTOCOL_TCP)
	{
		pBaseSocket = new CWinTcpSocket();
	}
	else
	{
		pBaseSocket = new CWinUdpSocket();

	}
#endif

#if _LINUX
	if (eProtocolType == NET_PROTOCOL_TCP)
	{
		pBaseSocket = new CLinuxTcpSocket();
	}
	else
	{
		pBaseSocket = new CLinuxUdpSocket();

	}
#endif

	if ( NULL == pBaseSocket )
	{
		// 没申请到内存
		return ERROR_NET_UNKNOWN;
	}

	pBaseSocket->SetBlockMode( m_clsThreadDealNetEvent.GetBlockMode() );
	m_clsClientChannel.SetLocalIPPort(pszBindIP, localport);
	m_clsClientChannel.SetReMoteIPPort(pszhost,unDesPort);


	//创建通道
	if (m_clsClientChannel.CreateChannel(pBaseSocket) != ERROR_BASE_SUCCESS)
	{
		//创建 通道失败
		pclsSocketChnl->CloseChannel();
		delete pclsSocketChnl;
		pclsSocketChnl = NULL;

		delete pBaseSocket;
		pBaseSocket = NULL;	

		char szRemoteIP[16]={0};
		UINT16 uiRemotePort = 0;
		char szLocalIP[16]={0};
		UINT16 uiLocalPort = 0;
		m_clsClientChannel.GetLocalIPPort(szLocalIP,uiLocalPort);
		m_clsClientChannel.GetReMoteIPPort(szRemoteIP,uiRemotePort);
		CTRLPRINTF( g_clsLogPtr,"创建通道失败传入通道参数,pszhost:%s, unDesPort:%u, pszBindIP:%s, localport:%u \n",pszhost, unDesPort,pszBindIP,localport );
		CTRLPRINTF( g_clsLogPtr,"创建通道失败客户端通道参数,szRemoteIP:%s, uiRemotePort:%u, szLocalIP:%s, uiLocalPort:%u \n",szRemoteIP, uiRemotePort,szLocalIP,uiLocalPort );
		return ERROR_NET_CREATE_CHANNEL_FAIL;
	}

	sockaddr_in struLocalAddr;
#if _WIN32
	INT32   iLocalAddrLen = sizeof(sockaddr_in);
#endif
#if _LINUX
	socklen_t   iLocalAddrLen = sizeof(sockaddr_in);
#endif
	getsockname( pBaseSocket->GetSocket(), (sockaddr*)&struLocalAddr, &iLocalAddrLen );
	pclsSocketChnl->SetLocalIPPort(inet_ntoa(struLocalAddr.sin_addr), (UINT16) ntohs(struLocalAddr.sin_port));

	//保存CBaseSocket
	pclsSocketChnl->SetCbaseSocketPoint(pBaseSocket);

	//将socketchannel存入vector容器
	m_clsThreadDealNetEvent.SaveSocketChannel(pclsSocketChnl);

	pclsSocketChnl->SetLogInstancePtr(m_clsThreadDealNetEvent.GetLogInstancePtr());

	CTRLPRINTF(m_clsThreadDealNetEvent.GetLogInstancePtr(), "通道%p创建成功, new socket %d, szRemoteIP:%s, \
		uiRemotePort:%u, szLocalIP:%s, uiLocalPort:%u\n ",pclsSocketChnl,pBaseSocket->GetSocket(),pszhost,unDesPort,
		inet_ntoa(struLocalAddr.sin_addr), (UINT16) ntohs(struLocalAddr.sin_port));

#if OPERATING_SYSTEM

	// select 什么都不需要做

#elif _WIN32

	//加入完成端口
	HANDLE hHandle = m_clsThreadDealNetEvent.AddToIoCompletionPort((HANDLE)pBaseSocket->GetSocket(), (DWORD)pclsSocketChnl->GetIOCPHandleData());
	if (hHandle == NULL)
	{
		pclsSocketChnl->CloseChannel();
		delete pclsSocketChnl;
		pclsSocketChnl = NULL;

		delete pBaseSocket;
		pBaseSocket = NULL;	
		CTRLPRINTF(m_clsThreadDealNetEvent.GetLogInstancePtr(), "通道%p加入完成端口失败, socket %d\n ",pclsSocketChnl,pBaseSocket->GetSocket());
		return ERROR_NET_CREATE_CHANNEL_FAIL;
	}
	//投掷第一次接收数据请求
	pclsSocketChnl->RecvData();

#else
	//linux

	//加入epoll
	m_clsThreadDealNetEvent.EpollCtrl( EPOLL_CTL_ADD,pBaseSocket->GetSocket(),pclsSocketChnl->GetEpollEvent());

	pclsSocketChnl->AddRefCount();

#endif
	//转换
	*pSocketChnl = (ISocketChannel*)pclsSocketChnl;


	return ERROR_BASE_SUCCESS;
}
예제 #22
0
void CEventDispatch::StartDispatch(uint32_t wait_timeout)
{
	fd_set read_set, write_set, excep_set;
	timeval timeout;
	timeout.tv_sec = 1;	//wait_timeout 1 second
	timeout.tv_usec = 0;

    while (running)
	{
		//_CheckTimer();
		//_CheckLoop();

		if (!m_read_set.fd_count && !m_write_set.fd_count && !m_excep_set.fd_count)
		{
			Sleep(MIN_TIMER_DURATION);
			continue;
		}

		m_lock.lock();
		FD_ZERO(&read_set);
		FD_ZERO(&write_set);
		FD_ZERO(&excep_set);
		memcpy(&read_set, &m_read_set, sizeof(fd_set));
		memcpy(&write_set, &m_write_set, sizeof(fd_set));
		memcpy(&excep_set, &m_excep_set, sizeof(fd_set));
		m_lock.unlock();

		if (!running)
			break;

		//for (int i = 0; i < read_set.fd_count; i++) {
		//	LOG__(NET,  "read fd: %d\n", read_set.fd_array[i]);
		//}
		int nfds = select(0, &read_set, &write_set, &excep_set, &timeout);
		if (nfds == SOCKET_ERROR)
		{
			//LOG__(NET,  "select failed, error code: %d\n", GetLastError());
			Sleep(MIN_TIMER_DURATION);
			continue;			// select again
		}
		if (nfds == 0)
		{
			continue;
		}
		for (u_int i = 0; i < read_set.fd_count; i++)
		{
			//LOG__(NET,  "select return read count=%d\n", read_set.fd_count);
			SOCKET fd = read_set.fd_array[i];
			CBaseSocket* pSocket = FindBaseSocket((net_handle_t)fd);
			if (pSocket)
			{
				pSocket->OnRead();
				pSocket->ReleaseRef();
			}
		}
		for (u_int i = 0; i < write_set.fd_count; i++)
		{
			//LOG__(NET,  "select return write count=%d\n", write_set.fd_count);
			SOCKET fd = write_set.fd_array[i];
			CBaseSocket* pSocket = FindBaseSocket((net_handle_t)fd);
			if (pSocket)
			{
				pSocket->OnWrite();
				pSocket->ReleaseRef();
			}
		}
		for (u_int i = 0; i < excep_set.fd_count; i++)
		{
			LOG__(NET,  _T("select return exception count=%d"), excep_set.fd_count);
			SOCKET fd = excep_set.fd_array[i];
			CBaseSocket* pSocket = FindBaseSocket((net_handle_t)fd);
			if (pSocket)
			{
				pSocket->OnClose();
				pSocket->ReleaseRef();
			}
		}
	}
}
예제 #23
0
int  CCommunication::GetHeart4Phone(CString argRequest, CString& argResponse)
{
	//建立连接
	CString  strShowInfo;
	argResponse.Empty();
	CBaseSocket  OclsBSocket ; 
	CBaseSocket* clsBSocket = &OclsBSocket; 
	//CBaseSocket* clsBSocket = CBaseSocket::GetInstance(); 

	if(NULL == clsBSocket) 
	{
		XWriteEventLog(_T("[CCommunication::GetHeart4Phone] CBaseSocket::GetInstance Failed.\r\n"));
		return -1;
	}

	int nRet = -1;
	SOCKET sendSocket, oldSock;
	nRet = clsBSocket->NoNagleCreateSocket(&sendSocket);
	if(0x00 != nRet)
	{
		nRet = GetLastError();

		strShowInfo.Format(_T("[CCommunication::GetHeart4Phone] InitializeAndCreateSocket ErrorNo=[%d].\r\n"), nRet);
		XWriteEventLog(strShowInfo);

		clsBSocket->CloseSocket( &sendSocket);
		return -2;
	}

	HANDLE hCurProcess = ::GetCurrentProcess();
	BOOL bIsOK = ::DuplicateHandle(
								hCurProcess, (HANDLE)oldSock, 
								hCurProcess, (LPHANDLE)&sendSocket, 
								0x00, FALSE,  ///关闭子进程继承标志
								DUPLICATE_CLOSE_SOURCE);

	if(FALSE == bIsOK)
	{
		sendSocket = oldSock;
		strShowInfo.Format(_T("[CCommunication::GetHeart4Phone] DuplicateHandle Failed\r\n"));
		XWriteEventLog(strShowInfo);
	}

	nRet = clsBSocket->ConnectToServer(&sendSocket, CCommunication::m_Port, CCommunication::m_Ip);
	if(0x00 != nRet)
	{	
		nRet = GetLastError();
		strShowInfo.Format(_T("[CCommunication::GetHeart4Phone] ConnectToServer ErrorNo=[%d].\r\n"), nRet);
		XWriteEventLog(strShowInfo);

		//m_nExceptionHeart++;
		clsBSocket->CloseSocket( &sendSocket);

		if( 10061 == nRet)
		{
			return -33;
		}
		return -3;
	}
	//发送命令
	if( ! argRequest.IsEmpty())
	{
		nRet = clsBSocket->SendMsg(&sendSocket, argRequest);
		if(0x00 != nRet)
		{
			nRet = GetLastError();
			strShowInfo.Format(_T("[CCommunication::GetHeart4Phone] SendMsg ErrorNo=[%d].\r\n"), nRet);
			XWriteEventLog(strShowInfo);

			//m_nExceptionHeart++;
			clsBSocket->CloseSocket( &sendSocket);
			return -4;
		}
	}else
	{
		XWriteEventLog(_T("[CCommunication::GetHeart4Phone] argRequest is Empty.\r\n"));
		return -5;
	}


	//接收返回值
	argResponse = "";
	clsBSocket->RecvMsg( &sendSocket, argResponse);
	//BYTE pRevStrTmp[1024 + 1] = {0};
	//int dword=0, iRevLen = 0;

	//Sleep(200);
	//do
	//{
	//	memset(pRevStrTmp, 0x00, sizeof(pRevStrTmp));
	//	dword = clsBSocket->RecvMsg( &sendSocket, pRevStrTmp, 1024);

	//	if(dword > 0x00 )
	//	{
	//		argResponse += (CHAR*)pRevStrTmp;
	//		iRevLen += dword;
	//		/// 接收完成 GetHeart4Phone
	//		if((-1) != argResponse.Find(_T("</res>"))) dword = 0x00;
	//	}

	//}while( dword != SOCKET_ERROR && dword != 0);

	//if(SOCKET_ERROR != dword)
	//{
	//	m_bPhoneStatus = TRUE;
	//}else
	//{
	//	//m_nExceptionHeart++;
	//	iRevLen = dword;
	//	nRet = GetLastError();
	//	strShowInfo.Format(_T("[CCommunication::GetHeart4Phone]  ErrorNo=[%d].\r\n"), nRet);
	//	XWriteEventLog(strShowInfo);
	//}

	//if(argResponse.IsEmpty())
	//{
	//	strShowInfo.Format(_T("[CCommunication::GetHeart4Phone]  Resp Data is Empty.\r\n"));
	//	XWriteEventLog(strShowInfo);
	//}
	//关闭连接
	clsBSocket->CloseSocket( &sendSocket);
	return  argResponse.GetLength();

}
예제 #24
0
int CCommunication::SendXmlToPhone(CString  argRequest, CString& argResponse,FunctionSocketCallBack CallBack,bool IsSetOutTime)
{
//	argRequest = ReplaceStr( argRequest, _T("&"), _T("&amp;") ); // zhaoshan [2012.01.11]

//  argRequest = ReplaceStr( argRequest, _T("<"), _T("&lt;") ); // zhaoshan [2012.02.27]

	//argRequest = ReplaceStr(argRequest, _T("&"), _T("&amp;") ); // zhaoshan [2012.01.11]

//  argRequest = ReplaceStr( argRequest, _T("\""), _T("&quot;") );

//  argRequest = ReplaceStr( argRequest, _T("\'"), _T("&apos; ") );


	CString FunName=GetRequestFuncationName(argRequest);
	if(CCommunication::m_nExceptionHeart > 0x03)
	{
		XWriteEventLog(_T("[CCommunication::SendXmlToPhone] %s CCommunication::ExceptionHeart > 0x02.\r\n"),FunName);
		return -1;
	}
	//建立连接
	CString  strShowInfo;
	argResponse.Empty();
	CBaseSocket  OclsBSocket ; 
	CBaseSocket* clsBSocket = &OclsBSocket; 
	//CBaseSocket* clsBSocket = CBaseSocket::GetInstance(); 

	if(NULL == clsBSocket) 
	{
		XWriteEventLog(_T("[CCommunication::SendXmlToPhone] CBaseSocket::GetInstance Failed.\r\n"));
		m_nExceptionCounter++;
		return -1;
	}

	int nRet = -1;
	SOCKET sendSocket;
	nRet = clsBSocket->InitializeAndCreateSocket(&sendSocket,IsSetOutTime);
	if(0x00 != nRet)
	{
		nRet = GetLastError();

		strShowInfo.Format(_T("[CCommunication::SendXmlToPhone] InitializeAndCreateSocket ErrorNo=[%d].\r\n"), nRet);
		XWriteEventLog(strShowInfo);

		clsBSocket->CloseSocket( &sendSocket);
		return -2;
	}
	
	nRet = clsBSocket->ConnectToServer(&sendSocket, CCommunication::m_Port, CCommunication::m_Ip);
	if(0x00 != nRet)
	{	
		nRet = GetLastError();
		strShowInfo.Format(_T("[CCommunication::SendXmlToPhone] FunName=[%s] ConnectToServer ErrorNo=[%d].\r\n"),FunName, nRet);
		XWriteEventLog(strShowInfo);

		m_nExceptionCounter++;
		clsBSocket->CloseSocket( &sendSocket);

		if( 10061 == nRet)
		{
			return -33;
		}
		return -3;
	}
	
	//发送命令
	if( ! argRequest.IsEmpty())
	{
		nRet = clsBSocket->SendMsg(&sendSocket, argRequest);
		if(0x00 != nRet)
		{
			int iRevLen=-4;
			nRet = GetLastError();
			::XWriteEventLog(_T("[CCommunication::SendXmlToPhone] %s Request Error=[%d]\n"),FunName,nRet);
			if(nRet == 10060)
				iRevLen=-6;      //Socket 超时返回值        

			clsBSocket->CloseSocket( &sendSocket);
			return iRevLen;
		}
	}else
	{
		XWriteEventLog(_T("[CCommunication::SendXmlToPhone] argRequest is Empty.\r\n"));
		return -5;
	}


	//接收返回值
	argResponse = "";

	clsBSocket->RecvMsg(&sendSocket,argResponse,CallBack);
	return  argResponse.GetLength();
}
예제 #25
0
int  CCommunication::CheckHeart4PhoneS2(CBaseSocket  & ttBSocket , SOCKET & sendSocket, CString argRequest, CString& argResponse)
{
		//////////////////////////////////////////////////////////////////////
	
		int nRet = 0;
		CString strShowInfo;
			//发送命令
		if( ! argRequest.IsEmpty())
		{
			//nRet = ttBSocket.SetCallFuncName(CCommunication::m_strCallFuncName);
			nRet = ttBSocket.SendMsg(&sendSocket, argRequest);
			if(0x00 != nRet)
			{
				nRet = GetLastError();
				strShowInfo.Format(_T("[CCommunication::CheckHeart4PhoneS2] SendMsg ErrorNo=[%d].\r\n"), nRet);
				XWriteEventLog(strShowInfo);

				m_nExceptionHeart++;
				//ttBSocket.CloseSocket( &sendSocket);
				return -4;
			}
		}else
		{
			XWriteEventLog(_T("[CCommunication::CheckHeart4PhoneS2] argRequest is Empty.\r\n"));
			return -5;
		}

		//接收返回值
		argResponse = "";
		BYTE pRevStrTmp[1024 + 1] = {0};
		int dword=0, iRevLen = 0;

		Sleep(200);
		do
		{
			memset(pRevStrTmp, 0x00, sizeof(pRevStrTmp));
			dword = ttBSocket.RecvMsg( &sendSocket, pRevStrTmp, 1024);

			if(dword > 0x00 )
			{
				argResponse += (CHAR*)pRevStrTmp;
				iRevLen += dword;
				/// 接收完成 CheckHeart4Phone
				if((-1) != argResponse.Find(_T("</res>"))) dword = 0x00;
			}else
			{
				Sleep(200);
			}

		}while( dword != SOCKET_ERROR && dword != 0);

		if(SOCKET_ERROR != dword)
		{
			m_bPhoneStatus = TRUE;
		}else
		{
			iRevLen = dword;
			m_nExceptionHeart++;

			nRet = GetLastError();
			strShowInfo.Format(_T("[CCommunication::CheckHeart4PhoneS2]  ErrorNo=[%d].\r\n"), nRet);
			XWriteEventLog(strShowInfo);
		}

		if(argResponse.IsEmpty())
		{
			strShowInfo.Format(_T("[CCommunication::CheckHeart4PhoneS2]  Resp Data is Empty.\r\n"));
			XWriteEventLog(strShowInfo);
		}

		//CString  strAckEnd = _T("===ack===");
		//nRet = ttBSocket.SendMsg(&sendSocket, strAckEnd);

	return  iRevLen;

}
예제 #26
0
void CEventDispatch::StartDispatch(uint32_t wait_timeout)
{
	fd_set read_set, write_set, excep_set;
	timeval timeout;
	timeout.tv_sec = 0;
	timeout.tv_usec = wait_timeout * 1000;	// 10 millisecond

    if(running)
        return;
    running = true;

    while (running){
		_CheckTimer();
        _CheckLoop();

		if (!m_read_set.fd_count && !m_write_set.fd_count && !m_excep_set.fd_count){
			Sleep(MIN_TIMER_DURATION);
			continue;
		}

		m_lock.lock();
		memcpy(&read_set, &m_read_set, sizeof(fd_set));
		memcpy(&write_set, &m_write_set, sizeof(fd_set));
		memcpy(&excep_set, &m_excep_set, sizeof(fd_set));
		m_lock.unlock();

		int nfds = select(0, &read_set, &write_set, &excep_set, &timeout);

		if (nfds == SOCKET_ERROR){
			Logger.Log(ERROR, "select failed, error code: %d", GetLastError());
			Sleep(MIN_TIMER_DURATION);
			continue;			// select again
		}

		if (nfds == 0){
			continue;
		}

		for (u_int i = 0; i < read_set.fd_count; i++){
			SOCKET fd = read_set.fd_array[i];
			CBaseSocket* pSocket = FindBaseSocket((net_handle_t)fd);
			if (pSocket){
				pSocket->OnRead();
				pSocket->ReleaseRef();
			}
		}

		for (u_int i = 0; i < write_set.fd_count; i++){
			SOCKET fd = write_set.fd_array[i];
			CBaseSocket* pSocket = FindBaseSocket((net_handle_t)fd);
			if (pSocket){
				pSocket->OnWrite();
				pSocket->ReleaseRef();
			}
		}

		for (u_int i = 0; i < excep_set.fd_count; i++){
			SOCKET fd = excep_set.fd_array[i];
			CBaseSocket* pSocket = FindBaseSocket((net_handle_t)fd);
			if (pSocket){
				pSocket->OnClose();
				pSocket->ReleaseRef();
			}
		}

	}
}
예제 #27
0
void CEventDispatch::StartDispatch()
{
    fd_set read_set, write_set, excep_set;
    timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = MIN_TIMER_DURATION * 1000;	// 10 millisecond

    while (true)
    {
        _CheckTimer();

        if (!m_read_set.fd_count && !m_write_set.fd_count && !m_excep_set.fd_count)
        {
            Sleep(MIN_TIMER_DURATION);
            continue;
        }

        m_lock.Lock();
        memcpy(&read_set, &m_read_set, sizeof(fd_set));
        memcpy(&write_set, &m_write_set, sizeof(fd_set));
        memcpy(&excep_set, &m_excep_set, sizeof(fd_set));
        m_lock.Unlock();

        int nfds = select(0, &read_set, &write_set, &excep_set, &timeout);

        if (nfds == SOCKET_ERROR)
        {
            log("select failed, error code: %d\n", GetLastError());
            Sleep(MIN_TIMER_DURATION);
            continue;			// select again
        }

        if (nfds == 0)
        {
            continue;
        }

        for (u_int i = 0; i < read_set.fd_count; i++)
        {
            //log("select return read count=%d\n", read_set.fd_count);
            SOCKET fd = read_set.fd_array[i];
            CBaseSocket* pSocket = FindBaseSocket((net_handle_t)fd);
            if (pSocket)
            {
                pSocket->OnRead();
                pSocket->ReleaseRef();
            }
        }

        for (u_int i = 0; i < write_set.fd_count; i++)
        {
            //log("select return write count=%d\n", write_set.fd_count);
            SOCKET fd = write_set.fd_array[i];
            CBaseSocket* pSocket = FindBaseSocket((net_handle_t)fd);
            if (pSocket)
            {
                pSocket->OnWrite();
                pSocket->ReleaseRef();
            }
        }

        for (u_int i = 0; i < excep_set.fd_count; i++)
        {
            //log("select return exception count=%d\n", excep_set.fd_count);
            SOCKET fd = excep_set.fd_array[i];
            CBaseSocket* pSocket = FindBaseSocket((net_handle_t)fd);
            if (pSocket)
            {
                pSocket->OnClose();
                pSocket->ReleaseRef();
            }
        }

    }
}