CHttpConnection& Syscall::GetHttp(MAHandle conn) { CConnection* cc = gConnections.find(conn); MYASSERT(cc, ERR_CONN_HANDLE_INVALID); CHttpConnection* http = cc->http(); MYASSERT(http, ERR_CONN_NOT_HTTP); return *http; }
HRESULT CNktDvTransportEngine::ConnectAgent(__in DWORD dwPid, __in DWORD dwTimeout) { CNktDvShutdownAutoLock cSdLock(&cShutdownMtx); CNktDvAutoCancellableFastMutex cLock(this, &cShutdownMtx); CConnection *lpConn; HRESULT hRes; if (cLock.IsLockHeld() == FALSE || cShutdownMtx.IsShuttingDown() != FALSE) return NKT_DVERR_Cancelled; if (cShutdownMtx.IsSystemActive() == FALSE) return E_FAIL; //not initialized if (dwPid == 0 || dwPid == dwMePid) return E_INVALIDARG; //check if connection already exists { CConnectionAutoRef cConnAutoRef(lpConn = FindConnectionAndAddRef(dwPid), FALSE); if (lpConn != NULL) return NKT_DVERR_AlreadyExists; } //---- lpConn = NKT_MEMMGR_NEW CConnection(this, dwPid); if (lpConn == NULL) return E_OUTOFMEMORY; //create pipe hRes = lpConn->Initialize(hIOCP, dwTimeout); if (FAILED(hRes)) { lpConn->Release(); return hRes; } //add to connection list cConnList.PushTail(lpConn); return S_OK; }
void CNet::SafeShutdwon(struct iocp_event * pEvent, s32 sdtags) { CConnection * pCConnection = (CConnection *) (pEvent->p); pCConnection->bShutdown = true; CAutoLock(&(pCConnection->sdlock)); pCConnection->nSDTags = pCConnection->nSDTags | sdtags; switch(pCConnection->nSDTags) { case CSD_RECV: shutdown(pEvent->s, SD_RECEIVE); break; case CSD_SEND: shutdown(pEvent->s, SD_SEND); break; case CSD_BOTH: shutdown(pEvent->s, SD_BOTH); break; default: ASSERT(false); return; } if (pCConnection->nSDTags == CSD_BOTH) { pCConnection->stream.clear(); pCConnection->nSDTags = 0; pCConnection->Clear(); m_ConnectPool.Recover(pCConnection); safe_close(pEvent); } closesocket(pCConnection->s); }
BOOL CConnectionMgr::CloseAllConnection() { CConnection *pConn = NULL; for(int i = 0; i < SVR_CONN_ID; i++) { pConn = m_StableConnList[i]; if(pConn != NULL) { pConn->Close(FALSE); } } for(std::set<CConnection*>::iterator itor = m_WaitConnList.begin(); itor != m_WaitConnList.end(); ++itor) { pConn = *itor; if(pConn != NULL) { pConn->Close(FALSE); } } for(stdext::hash_map<UINT64, CConnection*>::iterator itor = m_VarieableConnList.begin(); itor != m_VarieableConnList.end(); ++itor) { pConn = itor->second; if(pConn != NULL) { pConn->Close(FALSE); } } return TRUE; }
void OsiTransportTest::slotServerTSduReady(const CConnection* pConnection) { qDebug() << "OsiTransportTest::slotServerTSduReady, checkServerConnected = " << checkServerConnected << "; checkServerTransportConnected = " << checkServerTransportConnected; if (checkServerConnected) { if (!checkServerTransportConnected) { (const_cast<CConnection*>(pConnection))->listenForCR(); } else { // received data parsing CConnection* myconn = const_cast<CConnection*>(pConnection); if ( myconn->receive(m_serverRcvData) == true) { qDebug() << "OsiTransportTest::slotServerTSduReady: server data ready"; // Обработка данных и сброс буфера по окончании sendTestData(myconn); } else { qDebug() << "OsiTransportTest::slotServerTSduReady: server data is still not ready"; } } } }
int CMulticastSource::InitMulticast() { int iRet = IVS_FAIL; if (NULL == m_pChannelInfo) { IVS_LOG(IVS_LOG_ERR, "Init", "m_pChannelInfo = NULL."); return iRet; } // 连接socket; std::string strRemoteSendStreamIp; iRet = m_pChannelInfo->GetStreamIP(REMOTE_SEND_STREAM_IP, strRemoteSendStreamIp); if (strRemoteSendStreamIp.empty() || IVS_SUCCEED != iRet) { IVS_LOG(IVS_LOG_ERR, "Init", "UDP GetStreamIP failed. strRemoteSendStreamIp is empty"); return IVS_PARA_INVALID; } std::string strLocalRecvStreamIp; iRet = m_pChannelInfo->GetStreamIP(LOCAL_RECV_STREAM_IP, strLocalRecvStreamIp); if (strLocalRecvStreamIp.empty() || IVS_SUCCEED != iRet) { IVS_LOG(IVS_LOG_ERR, "Init", "Multicast GetStreamIP failed. strLocalRecvStreamIp is empty"); return IVS_PARA_INVALID; } for (int i = 0; i < SOCKET_COUNT; i++) { // 适配仅分配视频端口,未分配音频端口的问题; if ((AUDIO_RTCP_SOCKET == i || AUDIO_RTP_SOCKET == i) && m_pChannelInfo->IsOnlyVideo()) { IVS_LOG(IVS_LOG_ERR, "Init Multicast", "Udp source handle socket Index[%d] Only video port,do not set audio port for multicast", i); continue; } CConnection* pConn = m_pChannelInfo->GetConnection((SOCKET_TYPE)i); if (NULL == pConn) { iRet = IVS_FAIL; IVS_LOG(IVS_LOG_ERR, "Init", "Get connection from ChannelInfo failed, pConn = NULL ,socket index:%d", i); break; } unsigned int uiServerPort = 0; iRet = m_pChannelInfo->GetRemotePort((PORT_TYPE)i, uiServerPort); iRet = pConn->InitMulticast(strRemoteSendStreamIp.c_str(), uiServerPort, strLocalRecvStreamIp.c_str()); if (IVS_SUCCEED != iRet) { ShutDownSocket(); IVS_LOG(IVS_LOG_ERR, "Init", "Init multicast failed ,socket index:%d", i); break; } } return iRet; }
HRESULT CNktDvTransportEngine::SendMsg(__in DWORD dwPid, __inout NKT_DV_TMSG_COMMON *lpMsg, __in SIZE_T nMsgSize) { CNktDvShutdownAutoLock cSdLock(&cShutdownMtx); CConnectionAutoRef cConnAutoRef; CConnection *lpConn; CNktDvTransportOverlapped *lpOvr; HRESULT hRes; if (lpMsg == NULL) return E_POINTER; if (nMsgSize < sizeof(NKT_DV_TMSG_COMMON) || nMsgSize > NKT_DV_TRANSPORT_MAX_DATA_SIZE) return E_INVALIDARG; { CNktDvAutoCancellableFastMutex cLock(this, &cShutdownMtx); if (cLock.IsLockHeld() == FALSE || cShutdownMtx.IsShuttingDown() != FALSE) return NKT_DVERR_Cancelled; if (cShutdownMtx.IsSystemActive() == FALSE) return E_FAIL; //not initialized //find connection cConnAutoRef.Attach(lpConn = FindConnectionAndAddRef(dwPid), FALSE); if (lpConn == NULL) return NKT_DVERR_NotFound; NKT_DEBUGPRINTLNA(Nektra::dlTransport, ("%lu) TransportEngine[SendMsg]: Pid=%lu, Code=%lu, Id=%lu", ::GetTickCount(), dwPid, lpMsg->dwMsgCode & (~NKT_DV_TMSG_CODE_CALLBACK), lpMsg->dwMsgId & (~NKT_DV_TMSG_ID_CALLBACK))); } { CNktAutoFastMutex cConnAutoLock(lpConn); if (lpConn->nState != XSTATE_Connected) return E_FAIL; //not initialized //get a free buffer lpOvr = lpConn->GetBuffer(); if (lpOvr == NULL) return E_OUTOFMEMORY; //fill buffer nktMemCopy(lpOvr->sMsg.aBuf, lpMsg, nMsgSize); //do write prepare lpOvr->dwType = XTYPE_WriteRequest; lpOvr->nOrder = NktInterlockedIncrement(&(lpConn->nNextWriteOrder)); lpOvr->dwWrittenBytes = (DWORD)nMsgSize; lpConn->AddBufferToRwList(lpOvr); hRes = S_OK; if (::PostQueuedCompletionStatus(lpConn->hIocpCopy, 0, (ULONG_PTR)lpConn, &(lpOvr->sOvr)) == FALSE) hRes = NKT_HRESULT_FROM_LASTERROR(); } if (FAILED(hRes)) { lpConn->FreeBuffer(lpOvr); return hRes; } //done lpConn->AddRef(); NKT_DEBUGPRINTLNA(Nektra::dlTransport, ("%lu) TransportEngine[SendMsg]: Pid=%lu, Ovr=%IXh", ::GetTickCount(), dwPid, lpOvr)); return S_OK; }
// --------------------------------------------------------- // CConnection::NewL() // --------------------------------------------------------- // CConnection* CConnection::NewL() { CConnection* conn = new (ELeave) CConnection(); CleanupStack::PushL( conn ); conn->ConstructL(); CleanupStack::Pop( conn ); return conn; }
void Connection_Manager::send_dispatch_by_id(const string& data, uint32_t sid) { CConnection* conn = get_connection(sid); if(conn == NULL) connecting_by_id(data, sid); else conn->send(data); }
bool OnOutgoingConnection(ConnID id, const CConnection& conn, const CConnection& resolved_conn) final { if (resolved_conn.GetNetConfig().message_start == mainnet_message_start) printf("mainnet connected first\n"); else if (resolved_conn.GetNetConfig().message_start == testnet_message_start) printf("testnet connected first\n"); Shutdown(); return true; }
SOCKET CChannelInfo::GetSocket(SOCKET_TYPE enSocketType) { CConnection* pConnection = GetConnection(enSocketType); if (NULL == pConnection) { return INVALID_SOCKET; } return pConnection->GetSocket(); }
SYSCALL(void, maAccept(MAHandle conn)) { LOGST("maAccept %i", conn); CConnection* cc = gConnections.find(conn); MYASSERT(cc, ERR_CONN_HANDLE_INVALID); CServerSocket* ss = cc->server(); MYASSERT(ss, ERR_CONN_NOT_SERVER); MYASSERT((cc->state & CONNOP_ACCEPT) == 0, ERR_CONN_ALREADY_ACCEPTING); CSocket* newSock = new (ELeave) CSocket(gSocketServ, CSocket::EBlank); cc->state |= CONNOP_ACCEPT; StartConnOpL(CO_Accept::NewL(false, *this, conn, *cc, *ss, newSock)); }
CConnection* CConnection::Clone() { CHECK_NCBI_DBAPI(m_ds == NULL, "m_ds is not initialized"); CConnection *conn = new CConnection(CloneCDB_Conn(), m_ds); if( m_msgToEx ) conn->MsgToEx(true); ++m_connCounter; return conn; }
CMessage * CMyApplication::recvMessage ( int nMaxMS) { CConnection * pConn = m_pConnectionToReader; CMessage * pMessage; /* * Receive the message subject to a time limit */ pMessage = pConn->recvMessage(nMaxMS); /* * If LLRP::CConnection::recvMessage() returns NULL then there was * an error. In that case we try to print the error details. */ if(NULL == pMessage) { const CErrorDetails * pError = pConn->getRecvError(); printf("ERROR: recvMessage failed, %s\n", pError->m_pWhatStr ? pError->m_pWhatStr : "no reason given"); if(NULL != pError->m_pRefType) { printf("ERROR: ... reference type %s\n", pError->m_pRefType->m_pName); } if(NULL != pError->m_pRefField) { printf("ERROR: ... reference field %s\n", pError->m_pRefField->m_pName); } return NULL; } /* * Print the XML text for the inbound message if * verbosity is 2 or higher. */ if(1 < m_Verbose) { printf("\n===================================\n"); printf("INFO: Message received\n"); printXMLMessage(pMessage); } return pMessage; }
int ads_gm_import() { CProvidersCollection pc(true); StringPairs providersList = pc.ToStringPairs(); DlgProviders dlg(providersList, CWnd::FromHandle(adsw_acadMainWnd())); dlg.DoModal(); String providerName = dlg.GetProviderName(); if (providerName.length() == 0) { ads_retnil(); return( RSRSLT); } DlgProviderParam dlgProviders(pc.GetItem(providerName)); dlgProviders.DoModal(); CConnection * connection = dlgProviders.GetConnection(); if (connection != NULL) { FeatureClasses * featureClasses = CFeatureClass::GetFeatureClasses(connection); DlgLayers dlgLayers(featureClasses); dlgLayers.DoModal(); String featureClassName = dlgLayers.GetFeatureClassName(); if (featureClassName.length() == 0) { ads_retnil(); return( RSRSLT); } CFeatureClass * featureClass = featureClasses->operator [](featureClassName); if (featureClass == 0) { ads_retnil(); return( RSRSLT); } String extent = GetSelectedExtent(); connection->Open(); CFeatureReader featureReader = featureClass->SelectByExtent(extent); try { featureReader.DrawAll(); } catch (...) { } connection->Close(); delete featureClass; } delete connection; ads_retnil(); return( RSRSLT); }
int CMyApplication::sendMessage ( CMessage * pSendMsg) { CConnection * pConn = m_pConnectionToReader; /* * Print the XML text for the outbound message if * verbosity is 2 or higher. */ if(1 < m_Verbose) { printf("\n===================================\n"); printf("INFO: Sending\n"); printXMLMessage(pSendMsg); } /* * If LLRP::CConnection::sendMessage() returns other than RC_OK * then there was an error. In that case we try to print * the error details. */ if(RC_OK != pConn->sendMessage(pSendMsg)) { const CErrorDetails * pError = pConn->getSendError(); printf("ERROR: %s sendMessage failed, %s\n", pSendMsg->m_pType->m_pName, pError->m_pWhatStr ? pError->m_pWhatStr : "no reason given"); if(NULL != pError->m_pRefType) { printf("ERROR: ... reference type %s\n", pError->m_pRefType->m_pName); } if(NULL != pError->m_pRefField) { printf("ERROR: ... reference field %s\n", pError->m_pRefField->m_pName); } return -1; } /* * Victory */ return 0; }
void Syscall::CancelBluetoothConnections() { HashMap<CConnection>::TIteratorC itr = gConnections.begin(); LOGBT("%i connections.\n", gConnections.size()); while(itr.hasMore()) { const HashMap<CConnection>::Pair& p = itr.next(); CConnection* conn = p.value; DEBUG_ASSERT(conn != NULL); if(conn->isBluetooth()) { LOGBT("Canceling ops on connection %i.\n", p.key); conn->errorOverride = CONNERR_UNAVAILABLE; conn->CancelAll(); } } }
bool CNetClient::Connect(u_long dwAddr, u_short wPort) { sockaddr_in Addr; Addr.sin_family = AF_INET; Addr.sin_port = htons(wPort); Addr.sin_addr.s_addr = htonl(dwAddr); CConnection *pCon = new CConnection(&Addr); pCon->SetSink(this); //让网络线程处理本连接 m_WorkThread.PushConnection(pCon); send(m_WorkThread.GetNotify_Recv_Sock(), CLIENT_NOTIFY_STRING, strlen(CLIENT_NOTIFY_STRING), 0); log_info(APP_MODE" - CNetClient::Connect() addr=%u port=%hu", dwAddr, wPort); return true; }
int Lua_GetSocketRecvBuff(lua_State *L) { #ifdef _SERVER_ int iSocket = static_cast<int>(lua_tonumber(L, 1)); CConnection* pConn = CConnectionManager::GetSingleton().GetConn(iSocket); if (!pConn) { return 0; } lua_pushlightuserdata(L, pConn->GetRecvBuff()); #endif #ifdef _CLIENT_ lua_pushlightuserdata(L, CServerConnection::GetSingleton().GetRecvBuff()); #endif return 1; }
void CConnections::Remove(LPCTSTR sKey) { CConnection* pConnection =NULL; if (Lookup(sKey,pConnection)) { pConnection->Delete(); if (!RemoveKey(sKey)) { ASSERT(FALSE); } } }
CConnection* CConnection::NewLC(CSockSession* aSession, CPlayer* aPlayer, const CConnection& aExistingConnection, const Den::TSubSessionUniqueId aSubSessionUniqueId) /** Create a new CConnection object associated with the same interface as that of an existing CConnection object. @param aSession Session under which CConnection was created @param aExistingConnection Existing CConnection object whose interface to associate with @return pointer to new CConnection instance on success @exception leaves if could not allocate memory */ { CConnection* h = new (ELeave) CConnection(aSession, aPlayer, aExistingConnection.iTierId, aSubSessionUniqueId); CleanupStack::PushL(h); h->ConstructL(); h->CloneL(aExistingConnection); return h; }
CConnection* CConnection::NewLC(CSockSession *aSession, CPlayer* aPlayer, TUid aId, const Den::TSubSessionUniqueId aSubSessionUniqueId) /** Create a new CConnection instance @param aSession Session under which CConnection was created @param aId Type Id of CConnection @return pointer to new CConnection instance on success @exception leaves if could not allocate memory */ { CConnection* h = new (ELeave) CConnection(aSession, aPlayer, aId, aSubSessionUniqueId); CleanupStack::PushL(h); h->ConstructL(); ESOCK_DEBUG_REGISTER_GENERAL_NODE(ESockDebug::KConnectionNodeUid, h); return h; }
CNktDvTransportEngine::CConnection* CNktDvTransportEngine::FindConnectionAndAddRef(__in DWORD dwPid) { TNktLnkLst<CConnection>::Iterator it; CConnection *lpConn; //find process for (lpConn=it.Begin(cConnList); lpConn!=NULL; lpConn=it.Next()) { if (dwPid == lpConn->dwPid) { lpConn->AddRef(); return lpConn; } } return NULL; }
TInt32 CConnectionMgr::Run(TUInt32 runCnt) { TInt32 usedCnt = 0; CListener *pList = m_pListeners; m_nTimeNow = time(NULL); while (pList) { usedCnt += pList->Run(runCnt-usedCnt); if (usedCnt >= runCnt) { return usedCnt; } pList = pList->GetNext(); } usedCnt += m_connector.Run((runCnt-usedCnt)); TIOEvent *pEvent = m_netEventQueues.GetNetEvent(); while(pEvent) { TIOEvent event = *pEvent; m_netEventQueues.ConfirmHandleNetEvent(pEvent); CConnection *pConnection = m_conncectionPool.GetConectionByIdx(pEvent->m_connectionIdx); if (pConnection) { //先确认处理了消息,这样网络层如果有新事件,也会发事件通知. pConnection->OnAppRecved(); //由应用层调用,如果返回-1,则表示需要释放连接,把链接close ,并且放回connectionPool TInt32 ret = pConnection->AppRoutine(m_pBuff,m_buffSize); //不能先处理,再确认,因为,可能在处理完了,即上句执行完了,网络层又有了新事件,就会丢失. //pConnection->OnAppRecved(); pConnection->OnAppHandled(); if (ret < SUCCESS) { //pConnection->CloseConnection(); m_conncectionPool.ReleaseItem(pConnection); } } ++ usedCnt; if(usedCnt > runCnt) { break; } pEvent = m_netEventQueues.GetNetEvent(); } return usedCnt; }
CConnection* CNetManager::AssociateCompletePort( SOCKET hSocket ) { CConnection *pConnection = CConnectionMgr::GetInstancePtr()->CreateConnection(); pConnection->SetSocket(hSocket); pConnection->SetDataHandler(m_pBufferHandler); if(NULL == CreateIoCompletionPort((HANDLE)hSocket, m_hCompletePort, (ULONG_PTR)pConnection, 0)) { pConnection->Close(FALSE); return NULL; } return pConnection; }
BOOL CNetManager::WorkThread_ProcessEvent() { EventNode _EventNode; while(TRUE) { if(!m_DispatchEventList.Pop(_EventNode)) { continue; } CConnection *pConnection = (CConnection *)_EventNode.pPtr; if(pConnection == NULL) { if(_EventNode.dwEvent != 1) { CLog::GetInstancePtr()->AddLog("错误:取出一个空事件!"); } continue; } if(_EventNode.dwEvent == EVENT_READ) { if(!pConnection->HandleRecvEvent(0)) { //基本表明连接己断开,可以关闭连接了。 pConnection->Close(TRUE); CConnectionMgr::GetInstancePtr()->DeleteConnection(pConnection); } else { struct epoll_event EpollEvent; EpollEvent.data.ptr= pConnection; EpollEvent.events = EPOLLIN|EPOLLET; epoll_ctl(m_hCompletePort, EPOLL_CTL_MOD, pConnection->GetSocket(), &EpollEvent); } } else if(_EventNode.dwEvent == EVENT_WRITE) { } } return TRUE; }
void Connection_Manager::connecting_by_id(const string& data, uint32_t sid) { Server_Node_Map::iterator it = nodes_.find(sid); if(it != nodes_.end()) { CConnection* conn = NULL; if(it->second.conn == NULL) //建立一条新的TCP服务器连接 { conn = CONNECTION_POOL.pop_obj(); conn->set_index(0); conn->set_server_type(it->second.server_type); conn->set_server_id(it->second.server_id); //选取连接地址,目标地址为电信用电信网卡进行连接,依次类推 Inet_Addr src_addr, dst_addr; get_address_pair(it->second, src_addr, dst_addr); src_addr.set_port(0); //随机一个端口作为客户机端口 if(src_addr.get_ip() != INADDR_ANY) { src_addr.set_port(15000 + rand() % 15000); } CORE_INFO("connecting " << dst_addr << ", by local addr = " << src_addr << ", dst sid = " << sid); if(conn->connect(src_addr, dst_addr) != 0) { conn->close(); CONNECTION_POOL.push_obj(conn); CORE_DEBUG("push conn = " << this); CORE_ERROR("connect " << dst_addr << "failed!!"); return ; } it->second.conn = conn; } else { conn = it->second.conn; } if(conn->get_state() != CConnection::CONN_CONNECTED) //处于连接状态,缓冲到LIST中 it->second.strms.push_back(data); else conn->send(data); } else { CORE_ERROR("sid = " << sid << " error!!"); } }
void Connection_Manager::send_dispatch_by_id(CCorePacket& packet, uint32_t sid) { CConnection* conn = get_connection(sid); if(conn == NULL) { GAIN_BINSTREAM(strm); string data; *strm << packet; strm->bin_to_string(data); connecting_by_id(data, sid); RETURN_BINSTREAM(strm); } else { conn->send(packet); } }
IConnection* CConnection::CloneConnection(EOwnership ownership) { CHECK_NCBI_DBAPI(m_ds == NULL, "m_ds is not initialized"); CDB_Connection *cdbConn = CloneCDB_Conn(); CConnection *conn = new CConnection(m_ds, ownership); conn->m_modeMask = this->GetModeMask(); conn->m_forceSingle = this->m_forceSingle; conn->m_database = this->GetDatabase(); conn->m_connection = cdbConn; if( m_msgToEx ) conn->MsgToEx(true); conn->AddListener(m_ds); m_ds->AddListener(conn); return conn; }
BOOL CNetManager::WorkThread_Listen() { while(TRUE) { sockaddr_in Con_Addr; socklen_t nLen = sizeof(Con_Addr); memset(&Con_Addr, 0, sizeof(Con_Addr)); SOCKET hClientSocket = accept(m_hListenSocket, (sockaddr*)&Con_Addr, &nLen); if(hClientSocket == INVALID_SOCKET) { CLog::GetInstancePtr()->AddLog("accept 错误 原因:%s!", CommonSocket::GetLastErrorStr(CommonSocket::GetSocketLastError()).c_str()); break; } CommonSocket::SetSocketUnblock(hClientSocket); CConnection *pConnection = AssociateCompletePort(hClientSocket); if(pConnection != NULL) { CLog::GetInstancePtr()->AddLog("成功收到新连接,发送身份信息, 并提交数据请求!"); pConnection->SetConnectionOK(TRUE); SendIdentifyInfo(hClientSocket); #ifdef WIN32 if(!pConnection->DoReceive()) { pConnection->Close(FALSE); CConnectionMgr::GetInstancePtr()->DeleteConnection(pConnection); } #endif } else { CLog::GetInstancePtr()->AddLog("accept 错误 原因:%s!", CommonSocket::GetLastErrorStr(CommonSocket::GetSocketLastError()).c_str()); } } return TRUE; }