BOOL CFileSendDlg::OnInitDialog() { CDialog::OnInitDialog(); OnSend( ); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
void CAsyncSocketExLayer::CallEvent(int nEvent, int nErrorCode) { if (m_nCriticalError) return; m_nCriticalError=nErrorCode; switch (nEvent) { case FD_READ: case FD_FORCEREAD: if (GetLayerState()==connected) { if (nErrorCode) SetLayerState(aborted); OnReceive(nErrorCode); } break; case FD_WRITE: if (GetLayerState()==connected) { if (nErrorCode) SetLayerState(aborted); OnSend(nErrorCode); } break; case FD_CONNECT: if (GetLayerState()==connecting) { if (!nErrorCode) SetLayerState(connected); else SetLayerState(aborted); OnConnect(nErrorCode); } break; case FD_ACCEPT: if (GetLayerState()==listening) { if (!nErrorCode) SetLayerState(connected); else SetLayerState(aborted); OnAccept(nErrorCode); } break; case FD_CLOSE: if (GetLayerState()==connected) { if (nErrorCode) SetLayerState(aborted); else SetLayerState(closed); OnClose(nErrorCode); } break; } }
void CTransferSocket::OnIOThreadEvent(CIOThreadEvent& event) { if (!m_bActive || m_transferEndReason != none) return; if (m_transferMode == download) OnReceive(); else if (m_transferMode == upload) OnSend(); }
void SimulateClientMainFrame::OnMessageTextKeyup( wxKeyEvent& event ) { if(event.GetKeyCode()==WXK_RETURN) { wxCommandEvent e; OnSend(e); } }
void Connection::HandleSend( const boost::system::error_code & error, std::list< std::vector< uint8_t > >::iterator itr ) { if( error || HasError() || m_hive->HasStopped() ) { StartError( error ); } else { OnSend( *itr ); m_pending_sends.erase( itr ); StartSend(); } }
int APISocket::CSocket::Send() { if (!m_sock || errored) return 1; char *buff = new char[MAX_BUFFER]; int len = MAX_BUFFER; OnSend(buff, len); int ret = 0; if (len > 0) ret = Send(buff, len); delete [] buff; return ret; }
void CTransferSocket::OnIOThreadEvent() { if (!m_bActive || m_transferEndReason != TransferEndReason::none) { return; } if (m_transferMode == TransferMode::download) { OnReceive(); } else if (m_transferMode == TransferMode::upload) { OnSend(); } }
DWORD OnCommand(HWND hDlg, WPARAM wParam, LPARAM lParam) { switch( LOWORD( wParam ) ) { case IDC_BTN_LOGIN: OnLogin(hDlg); break; case IDC_BTN_SEND: OnSend(hDlg); break; case ID_LOGOUT: OnLogOut(hDlg); break; case ID_EXIT: case IDCANCEL: OnExit(hDlg); break; } return TRUE; }
void DataSocket::OnConnect(int nErrorCode) { if (nErrorCode) { m_nStatus = XFERMODE_ERROR; m_pConnectSocket->SendResponse("425 Can't open data connection."); // destroy this socket AfxGetThread()->PostThreadMessage(WM_THREADMSG, 0, 0); } else { switch (m_nTransferType) { case 0: // List Directory m_nStatus = XFERMODE_LIST; m_bConnected = TRUE; OnSend(0); break; case 1: // Send File if (PrepareSendFile(m_strData)) { m_nStatus = XFERMODE_SEND; m_bConnected = TRUE; } else { Close(); } break; case 2: // Receive File if (PrepareReceiveFile(m_strData)) { m_nStatus = XFERMODE_RECEIVE; m_bConnected = TRUE; } else { Close(); m_pConnectSocket->SendResponse("450 can't access file."); // destroy this socket AfxGetThread()->PostThreadMessage(WM_THREADMSG, 0, 0); // upload failed ((ConnectThread *)AfxGetThread())->UpdateStatistic(FTPSTAT_UPLOADFAILED); } break; } } CAsyncSocket::OnConnect(nErrorCode); }
void CTlsSocket::OnSocketEvent(wxSocketEvent& event) { wxASSERT(m_pSocket); if (!m_session) return; if (event.GetId() != m_pSocketBackend->GetId()) return; switch (event.GetSocketEvent()) { case wxSOCKET_INPUT: OnRead(); break; case wxSOCKET_OUTPUT: OnSend(); break; case wxSOCKET_LOST: { m_canCheckCloseSocket = true; char tmp[100]; m_pSocketBackend->Peek(&tmp, 100); if (!m_pSocketBackend->Error()) { int lastCount = m_pSocketBackend->LastCount(); if (lastCount) m_pOwner->LogMessage(Debug_Verbose, _T("CTlsSocket::OnSocketEvent(): pending data, postponing wxSOCKET_LOST")); else m_socketClosed = true; OnRead(); if (lastCount) return; } m_pOwner->LogMessage(Debug_Info, _T("CTlsSocket::OnSocketEvent(): wxSOCKET_LOST received")); //Uninit(); wxSocketEvent evt(GetId()); evt.m_event = wxSOCKET_LOST; wxPostEvent(m_pEvtHandler, evt); } break; default: break; } }
void CServerWorkFlow::OnMessage(MSG & msg) { switch(msg.message) { case WM_SEND: OnSend(msg.wParam, msg.lParam); break; case WM_RECEIVE: OnReceive(msg.wParam, msg.lParam); break; default: break; } CThread::OnMessage(msg); }
void CRealControlSocket::OnSocketEvent(CSocketEvent &event) { if (!m_pBackend) return; switch (event.GetType()) { case CSocketEvent::hostaddress: { const wxString& address = event.GetData(); LogMessage(MessageType::Status, _("Connecting to %s..."), address); } break; case CSocketEvent::connection_next: if (event.GetError()) LogMessage(MessageType::Status, _("Connection attempt failed with \"%s\", trying next address."), CSocket::GetErrorDescription(event.GetError())); break; case CSocketEvent::connection: if (event.GetError()) { LogMessage(MessageType::Status, _("Connection attempt failed with \"%s\"."), CSocket::GetErrorDescription(event.GetError())); OnClose(event.GetError()); } else { if (m_pProxyBackend && !m_pProxyBackend->Detached()) { m_pProxyBackend->Detach(); m_pBackend = new CSocketBackend(this, m_pSocket); } OnConnect(); } break; case CSocketEvent::read: OnReceive(); break; case CSocketEvent::write: OnSend(); break; case CSocketEvent::close: OnClose(event.GetError()); break; default: LogMessage(MessageType::Debug_Warning, _T("Unhandled socket event %d"), event.GetType()); break; } }
void CTlsSocket::OnSocketEvent(CSocketEvent& event) { wxASSERT(m_pSocket); if (!m_session) return; switch (event.GetType()) { case CSocketEvent::read: OnRead(); break; case CSocketEvent::write: OnSend(); break; case CSocketEvent::close: { m_canCheckCloseSocket = true; char tmp[100]; int error; int peeked = m_pSocketBackend->Peek(&tmp, 100, error); if (peeked >= 0) { if (peeked > 0) m_pOwner->LogMessage(Debug_Verbose, _T("CTlsSocket::OnSocketEvent(): pending data, postponing close event")); else { m_socket_eof = true; m_socketClosed = true; } OnRead(); if (peeked) return; } m_pOwner->LogMessage(Debug_Info, _T("CTlsSocket::OnSocketEvent(): close event received")); //Uninit(); CSocketEvent *evt = new CSocketEvent(m_pEvtHandler, this, CSocketEvent::close); CSocketEventDispatcher::Get().SendEvent(evt); } break; default: break; } }
void debugmodel::OnBnClickedButton5() { // TODO: 急停 static int flage = 1; char data[] = "1234567"; data[0] = ADDFIRST; data[2] = ADDEND; CString tmp; m_garage_id.GetWindowText(tmp); if (tmp == "") return; data[1] = _wtoi(tmp.GetBuffer(0)); if (flage) { data[3] = STOP; flage = 0; } else { data[3] = RESET; flage = 1; } //m_row.GetWindowText(tmp); data[4] = 0;// _wtoi(tmp.GetBuffer(0)); //m_col.GetWindowText(tmp); data[5] = 0;// _wtoi(tmp.GetBuffer(0)); data[6] = (data[1] + data[3] + data[4] + data[5]) % CHECKMOD; TESTPUTSEND OnSend(data, 7); Sleep(100); memset(recstr, '\0', COMLEN); OnReceive(recstr, 4); TESTPUTRECN //putinfo(recstr); }
void CEMSocket::SendPacket(Packet *pPacket, bool bDeletePacket/*=true*/, bool bControlPacket/*=true*/) { // EMTrace("CEMSocket::OnSenPacked1 linked: %i, controlcount %i, standardcount %i, isbusy: %i",m_bLinkedPackets, m_controlPacketQueue.GetCount(), m_standardPacketQueue.GetCount(), IsBusy()); if (!bDeletePacket) { ASSERT (!pPacket->IsSplit()); Packet *pPacketCopy = new Packet(pPacket->m_eOpcode,pPacket->m_dwSize); memcpy2(pPacketCopy->m_pcBuffer,pPacket->m_pcBuffer,pPacket->m_dwSize); pPacket = pPacketCopy; } if (!IsConnected() || IsBusy() || (m_bLinkedPackets && bControlPacket)) { if (bControlPacket) m_controlPacketQueue.AddTail(pPacket); else m_standardPacketQueue.AddTail(pPacket); return; } bool bCheckControlQueue = false; if (pPacket->IsLastSplit()) { m_bLinkedPackets = false; bCheckControlQueue = true; } else if (pPacket->IsSplit()) { m_bLinkedPackets = true; } else if (m_bLinkedPackets) { ASSERT(false); } // EMTrace("CEMSocket::OnSenPacked2 linked: %i, controlcount %i, standardcount %i, isbusy: %i",m_bLinkedPackets, m_controlPacketQueue.GetCount(), m_standardPacketQueue.GetCount(), IsBusy()); Send(pPacket->DetachPacket(), pPacket->GetRealPacketSize()); delete pPacket; if (!IsBusy() && bCheckControlQueue) OnSend(0); }
void CTlsSocket::OnSocketEvent(CSocketEventSource*, SocketEventType t, int error) { if (!m_session) return; switch (t) { case SocketEventType::read: OnRead(); break; case SocketEventType::write: OnSend(); break; case SocketEventType::close: { m_canCheckCloseSocket = true; char tmp[100]; int peeked = m_pSocketBackend->Peek(&tmp, 100, error); if (peeked >= 0) { if (peeked > 0) m_pOwner->LogMessage(MessageType::Debug_Verbose, _T("CTlsSocket::OnSocketEvent(): pending data, postponing close event")); else { m_socket_eof = true; m_socketClosed = true; } OnRead(); if (peeked) return; } m_pOwner->LogMessage(MessageType::Debug_Info, _T("CTlsSocket::OnSocketEvent(): close event received")); //Uninit(); m_pEvtHandler->send_event<CSocketEvent>(this, SocketEventType::close, 0); } break; default: break; } }
void debugmodel::OnBnClickedButton2() { // TODO: 取车 char data[] = "1234567"; data[0] = ADDFIRST; data[2] = ADDEND; CString tmp; m_garage_id.GetWindowText(tmp); if (tmp == "") return; data[1] = _wtoi(tmp.GetBuffer(0)); data[3] = DELETECAR; m_row.GetWindowText(tmp); if (tmp == "") return; data[4] = _wtoi(tmp.GetBuffer(0)); m_col.GetWindowText(tmp); if (tmp == "") return; data[5] = _wtoi(tmp.GetBuffer(0)); data[6] = (data[1] + data[3] + data[4] + data[5]) % CHECKMOD; TESTPUTSEND OnSend(data, 7); Sleep(100); memset(recstr, '\0', COMLEN); OnReceive(recstr, 4); TESTPUTRECN //putinfo(recstr); }
/*======================================================================================== FUNCTION: LBaseSock::WindowProc() DESCRIPT: Event handler window procedure. RETURN : ARGUMENT: uMsg : (i)Message ID wParam: (i)Message parameter 1 lParam: (i)Message parameter 2 UPDATE : 2004/07/01, In-hyeok Paek; First work! ========================================================================================*/ LRESULT LBaseSock::WindowProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { int nErr; // Socket error code if( uMsg == WM_SOCK_SOCKET ) { nErr = WSAGETASYNCERROR( lParam ); switch( WSAGETSELECTEVENT( lParam ) ) { case FD_ACCEPT: OnAccept( nErr ); break; case FD_CONNECT: ::KillTimer( m_hWnd, IDT_SOCK_CONNECT ); OnConnect( nErr ); break; case FD_CLOSE: OnClose( nErr ); break; case FD_READ: OnReceive( nErr ); break; case FD_WRITE: OnSend( nErr ); break; } return 0L; } else if( uMsg == WM_TIMER ) { if( wParam == IDT_SOCK_CONNECT ) { if( m_Sock != INVALID_SOCKET ) { closesocket( m_Sock ); m_Sock = INVALID_SOCKET; } m_nLastErr = WSAETIMEDOUT; OnConnect( WSAETIMEDOUT ); return 0L; } } return ::DefWindowProc( m_hWnd, uMsg, wParam, lParam ); }
void WAsyncSocket::SocketMessage(WPARAM wparam,LPARAM lparam) { // wparam is the socket number, lparam is the event code (lower word) and error code (upper word) int event_code=WSAGETSELECTEVENT(lparam); // lower word of lparam int error_code=WSAGETSELECTERROR(lparam); // upper word of lparam switch(event_code) { case FD_CONNECT: { OnConnect(error_code); break; } case FD_ACCEPT: { OnAccept(error_code); break; } case FD_READ: { OnReceive(error_code); break; } case FD_WRITE: { OnSend(error_code); break; } case FD_CLOSE: { OnClose(error_code); break; } default: { // Unknown Socket Message break; } } }
void CRealControlSocket::OnSocketEvent(CSocketEventSource*, SocketEventType t, int error) { if (!m_pBackend) return; switch (t) { case SocketEventType::connection_next: if (error) LogMessage(MessageType::Status, _("Connection attempt failed with \"%s\", trying next address."), CSocket::GetErrorDescription(error)); SetAlive(); break; case SocketEventType::connection: if (error) { LogMessage(MessageType::Status, _("Connection attempt failed with \"%s\"."), CSocket::GetErrorDescription(error)); OnClose(error); } else { if (m_pProxyBackend && !m_pProxyBackend->Detached()) { m_pProxyBackend->Detach(); m_pBackend = new CSocketBackend(this, *m_pSocket, engine_.GetRateLimiter()); } OnConnect(); } break; case SocketEventType::read: OnReceive(); break; case SocketEventType::write: OnSend(); break; case SocketEventType::close: OnClose(error); break; default: LogMessage(MessageType::Debug_Warning, _T("Unhandled socket event %d"), t); break; } }
void CTransferSocket::TriggerPostponedEvents() { wxASSERT(m_bActive); if (m_postponedReceive) { m_pControlSocket->LogMessage(::Debug_Verbose, _T("Executing postponed receive")); m_postponedReceive = false; OnReceive(); if (m_transferEndReason != none) return; } if (m_postponedSend) { m_pControlSocket->LogMessage(::Debug_Verbose, _T("Executing postponed send")); m_postponedSend = false; OnSend(); if (m_transferEndReason != none) return; } if (m_onCloseCalled) OnClose(0); }
void CExternalIPResolver::OnSocketEvent(CSocketEvent& event) { if (!m_pSocket) return; switch (event.GetType()) { case CSocketEvent::read: OnReceive(); break; case CSocketEvent::connection: OnConnect(event.GetError()); break; case CSocketEvent::close: OnClose(); break; case CSocketEvent::write: OnSend(); break; default: break; } }
// CBacnetProgramEdit message handlers LRESULT CBacnetProgramEdit::OnHotKey(WPARAM wParam,LPARAM lParam) { if(Run_once_mutex == true) //If already exist some function run,it can't show another one; return -1; if (wParam==KEY_F2) { Run_once_mutex = true; OnSend(); Run_once_mutex = false; } else if(wParam == KEY_F3) { Run_once_mutex = true; OnClear(); Run_once_mutex = false; } else if(wParam == KEY_F7) { Run_once_mutex = true; OnLoadfile(); Run_once_mutex = false; } else if(wParam == KEY_F6) { Run_once_mutex = true; OnSavefile(); Run_once_mutex = false; } else if(wParam == KEY_F8) { Run_once_mutex = true; OnRefresh(); Run_once_mutex = false; } return 0; }
void CTransferSocket::TriggerPostponedEvents() { assert(m_bActive); if (m_postponedReceive) { controlSocket_.LogMessage(MessageType::Debug_Verbose, _T("Executing postponed receive")); m_postponedReceive = false; OnReceive(); if (m_transferEndReason != TransferEndReason::none) { return; } } if (m_postponedSend) { controlSocket_.LogMessage(MessageType::Debug_Verbose, _T("Executing postponed send")); m_postponedSend = false; OnSend(); if (m_transferEndReason != TransferEndReason::none) { return; } } if (m_onCloseCalled) { OnClose(0); } }
void debugmodel::OnBnClickedButton3() { // TODO: 获取位置 char data[] = "1234567"; data[0] = ADDFIRST; data[2] = ADDEND; CString tmp; m_garage_id.GetWindowText(tmp); if (tmp == "") return; data[1] = _wtoi(tmp.GetBuffer(0)); data[3] = GETLOCATION; //m_row.GetWindowText(tmp); data[4] = 0;// _wtoi(tmp.GetBuffer(0)); //m_col.GetWindowText(tmp); data[5] = 0;// _wtoi(tmp.GetBuffer(0)); data[6] = (data[1] + data[3] + data[4] + data[5]) % CHECKMOD; TESTPUTSEND OnSend(data, 7); Sleep(100); memset(recstr, '\0', COMLEN); OnReceive(recstr, 4); TESTPUTRECN //putinfo(recstr); tmp.Format(_T("第%d行第%d列"),recstr[2],recstr[1]); m_location.SetWindowTextW(tmp); }
void EvalPane::OnEnter(wxCommandEvent& event) { if ( !m_textCtrlExpression->IsEmpty() ) { OnSend( event ); } }
void CTransferSocket::OnSocketEvent(CSocketEvent &event) { if (m_pProxyBackend) { switch (event.GetType()) { case CSocketEvent::connection: { const int error = event.GetError(); if (error) { m_pControlSocket->LogMessage(::Error, _("Proxy handshake failed: %s"), CSocket::GetErrorDescription(error).c_str()); TransferEnd(failure); } else { delete m_pProxyBackend; m_pProxyBackend = 0; OnConnect(); } } return; case CSocketEvent::close: { const int error = event.GetError(); m_pControlSocket->LogMessage(::Error, _("Proxy handshake failed: %s"), CSocket::GetErrorDescription(error).c_str()); TransferEnd(failure); } return; default: // Uninteresting return; } return; } if (m_pSocketServer) { if (event.GetType() == CSocketEvent::connection) OnAccept(event.GetError()); else m_pControlSocket->LogMessage(::Debug_Info, _T("Unhandled socket event %d from listening socket"), event.GetType()); return; } switch (event.GetType()) { case CSocketEvent::connection: OnConnect(); break; case CSocketEvent::read: OnReceive(); break; case CSocketEvent::write: OnSend(); break; case CSocketEvent::close: OnClose(event.GetError()); break; case CSocketEvent::hostaddress: // Booooring. No seriously, we connect by IP already, nothing to resolve break; default: m_pControlSocket->LogMessage(::Debug_Info, _T("Unhandled socket event %d"), event.GetType()); break; } }
/// /// /// this is the thread which manages a single output connection. /// void OutputTarget::Body () { /// implicit wait mutex for this thread. /// see overridden Begin() #if defined(__QNX6__) || defined(__LINUX__) signal (SIGPIPE, SIG_IGN); #endif int success = YARP_OK; NewFragmentHeader header; BlockSender sender; CountedPtr<Sendable> p_local_sendable; ACE_OS::memset (cmdname, 0, 2*YARP_STRING_LEN); msg_type = 0; /// needs to know what is the protocol of the owner. switch (protocol_type) { case YARP_QNET: { ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : starting a QNET sender thread\n")); /// LATER: must do proper bailout if locate fails. /// target_pid = YARPNameService::LocateName (GetLabel().c_str()); target_pid->setRequireAck(GetRequireAck()); if (target_pid->getServiceType() != protocol_type) { /// problems. ACE_DEBUG ((LM_DEBUG, "troubles locating %s, the protocol is wrong\n", GetLabel().c_str())); YARPNameService::DeleteName(target_pid); target_pid = NULL; active = 0; deactivated = 1; PostMutex (); return; } YARPEndpointManager::CreateOutputEndpoint (*target_pid); YARPEndpointManager::ConnectEndpoints (*target_pid, own_name); } break; case YARP_TCP: { ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : starting a TCP sender thread\n")); target_pid = YARPNameService::LocateName (GetLabel().c_str(), network_name.c_str()); target_pid->setRequireAck(GetRequireAck()); /* There is some kind of hack going on here that prevents a clean use of nameserver (registering ports with the protocol they actually use). Adding a workaround. */ int use_workaround = 0; if (target_pid->isConsistent(YARP_TCP)) { use_workaround = 1; } if (!(use_workaround|| target_pid->isConsistent(YARP_UDP))) { if (target_pid->getServiceType()==YARP_NO_SERVICE_AVAILABLE) { ACE_DEBUG ((LM_INFO, "*** FAILED to make connection to %s, port not found\n",GetLabel().c_str())); } else { ACE_DEBUG ((LM_INFO, "***** OutputTarget::Body : can't connect - target on different network, output thread 0x%x bailing out\n", GetIdentifier())); } YARPNameService::DeleteName(target_pid); target_pid = NULL; active = 0; deactivated = 1; PostMutex (); return; } #ifndef DEBUG_DISABLE_SHMEM /// involves a query to dns or to the /etc/hosts file. char myhostname[YARP_STRING_LEN]; getHostname (myhostname, YARP_STRING_LEN); ACE_INET_Addr local ((u_short)0, myhostname); /// this test is carried out by the nameserver relying on the /// subnetwork structure. char iplocal[17]; ACE_OS::memset (iplocal, 0, 17); ACE_OS::memcpy (iplocal, local.get_host_addr(), 17); #ifdef USE_YARP2 // Test for locality is broken. // Is test for same-machine sufficient? bool same_machine = YARPNameService::VerifySame (((YARPUniqueNameSock *)target_pid)->getAddressRef().get_host_addr(), iplocal, network_name); #else bool same_machine = YARPNameService::VerifyLocal (((YARPUniqueNameSock *)target_pid)->getAddressRef().get_host_addr(), iplocal, network_name.c_str()); #endif ///if (((YARPUniqueNameSock *)target_pid)->getAddressRef().get_ip_address() == local.get_ip_address()) bool accepted = true; #ifdef USE_YARP2 // YARP2 extension if (same_machine&&allow_shmem) { accepted = (YARPNameService::CheckProperty(GetLabel().c_str(),"accepts", "shmem"))!=0; if (!accepted) { ACE_DEBUG ((LM_DEBUG, "switching to SHMEM mode is prohibited\n")); } } // YARP2 extension ends #endif if (same_machine && allow_shmem && accepted) { /// going into SHMEM mode. protocol_type = YARP_SHMEM; target_pid->setServiceType (YARP_SHMEM); target_pid->setRequireAck(GetRequireAck()); /// ACE_DEBUG ((LM_DEBUG, "$$$$$ OutputTarget::Body : this goes into SHMEM mode\n")); } else #endif { /// /// LATER: do proper check. /// must always succeed. Any protocol is fine but QNET /// for creating a socket connection. if (target_pid->getServiceType() != protocol_type && target_pid->getServiceType() != YARP_UDP) { /// problems. ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : troubles locating %s, the protocol is wrong\n", GetLabel().c_str())); YARPNameService::DeleteName(target_pid); target_pid = NULL; ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier())); active = 0; deactivated = 1; PostMutex (); return; ///target_pid->invalidate(); } protocol_type = YARP_TCP; target_pid->setServiceType (YARP_TCP); target_pid->setRequireAck(GetRequireAck()); } YARPEndpointManager::CreateOutputEndpoint (*target_pid); YARPEndpointManager::ConnectEndpoints (*target_pid, own_name); //#ifdef DEBUG_DISABLE_SHMEM # ifdef YARP_TCP_NO_DELAY /// disables Nagle's algorithm... if (protocol_type == YARP_TCP) YARPEndpointManager::SetTCPNoDelay (*target_pid); # endif //#endif } break; case YARP_UDP: { ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : starting a UDP sender thread\n")); target_pid = YARPNameService::LocateName (GetLabel().c_str(), network_name.c_str()); target_pid->setRequireAck(GetRequireAck()); if (!target_pid->isConsistent(YARP_UDP)) { if (target_pid->getServiceType()==YARP_NO_SERVICE_AVAILABLE) { ACE_DEBUG ((LM_INFO, "*** FAILED to make connection to %s, port not found\n",GetLabel().c_str())); } else { ACE_DEBUG ((LM_INFO, "***** OutputTarget::Body : can't connect - target on different network, output thread 0x%x bailing out\n", GetIdentifier())); } YARPNameService::DeleteName(target_pid); target_pid = NULL; active = 0; deactivated = 1; PostMutex (); return; } #ifndef DEBUG_DISABLE_SHMEM char myhostname[YARP_STRING_LEN]; getHostname (myhostname, YARP_STRING_LEN); ACE_INET_Addr local ((u_short)0, myhostname); char iplocal[17]; ACE_OS::memset (iplocal, 0, 17); ACE_OS::memcpy (iplocal, local.get_host_addr(), 17); /// this test is carried out by the name server. bool same_machine = YARPNameService::VerifyLocal (((YARPUniqueNameSock *)target_pid)->getAddressRef().get_host_addr(), iplocal, network_name.c_str()); ///if (((YARPUniqueNameSock *)target_pid)->getAddressRef().get_ip_address() == local.get_ip_address()) if (same_machine && allow_shmem) { /// going into SHMEM mode. protocol_type = YARP_SHMEM; ((YARPUniqueNameSock *)target_pid)->setServiceType (YARP_SHMEM); target_pid->setRequireAck(GetRequireAck()); /// ACE_DEBUG ((LM_DEBUG, "$$$$$ OutputTarget::Body : this goes into SHMEM mode\n")); } else { /// needed because the port changes from that of the incoming call /// it is used to accept data (pretend a connection to the remote). if (target_pid->getServiceType() != YARP_UDP) { /// problems. ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : troubles locating %s, the protocol is wrong\n", GetLabel().c_str())); YARPNameService::DeleteName(target_pid); target_pid = NULL; ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier())); active = 0; deactivated = 1; PostMutex (); return; ///target_pid->invalidate(); } } #else if (target_pid->getServiceType() != YARP_UDP) { /// problems. ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : troubles locating %s, the protocol is wrong\n", GetLabel().c_str())); ///target_pid->invalidate(); YARPNameService::DeleteName(target_pid); target_pid = NULL; ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier())); active = 0; deactivated = 1; PostMutex (); return; } #endif YARPEndpointManager::CreateOutputEndpoint (*target_pid); YARPEndpointManager::ConnectEndpoints (*target_pid, own_name); } break; case YARP_MCAST: { ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : starting a MCAST sender thread\n")); /// MCAST is different! Locate prepares the MCAST group and registers it. /// additional commands are sent to "clients" to ask to join the specific group. /// ALSO: VerifySame had been called before actually running the thread. target_pid = YARPNameService::LocateName(GetLabel().c_str(), network_name.c_str(), YARP_MCAST); target_pid->setRequireAck(GetRequireAck()); YARPEndpointManager::CreateOutputEndpoint (*target_pid); if (target_pid->getServiceType() != YARP_MCAST) { /// problems. ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : troubles locating %s, the protocol is wrong\n", GetLabel().c_str())); ///target_pid->invalidate(); YARPNameService::DeleteName(target_pid); target_pid = NULL; ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier())); active = 0; deactivated = 1; PostMutex (); return; } } break; } /// this wait for initialization. PostMutex (); YARP_DBG(THIS_DBG) ((LM_DEBUG, "Output target after initialization section\n")); /// if the address is not valid, terminates the thread. if (!target_pid->isValid()) { /// ACE_DEBUG ((LM_DEBUG, "***** OutputTarget, troubles, perhaps a process died without unregistering\n")); ACE_DEBUG ((LM_DEBUG, "***** OutputTarget, can't connect to the remote endpoint\n")); YARPNameService::DeleteName(target_pid); target_pid = NULL; ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier())); active = 0; deactivated = 1; PostMutex (); return; } while (!deactivated) { YARP_DBG(THIS_DBG) ((LM_DEBUG, "Waiting for sema to send\n")); something_to_send.Wait(); YARP_DBG(THIS_DBG) ((LM_DEBUG, "Done waiting for sema to send\n")); WaitMutex(); if (deactivate) { active = 0; deactivated = 1; PostMutex (); continue; } /// /// MCAST commands follow: /// - these are sent and processed by contacting the TCP channel of the port. if (protocol_type == YARP_MCAST) { /// LATER: need to figure out whether this is always ok. /// multiple connection requests might overlap? YARP_DBG(THIS_DBG) ((LM_DEBUG, "-------- msg_type is %d\n", msg_type)); /// process connect/disconnect messages. switch (msg_type) { case 1: { /// connect YARPUniqueNameID* udp_channel = YARPNameService::LocateName(cmdname, network_name.c_str(), YARP_UDP); YARPEndpointManager::ConnectEndpoints (*udp_channel, own_name); YARPNameService::DeleteName (udp_channel); } break; case 2: { /// disconnect YARPUniqueNameID* udp_channel = YARPNameService::LocateName(cmdname, network_name.c_str(), YARP_UDP); if (udp_channel->getServiceType() == YARP_NO_SERVICE_AVAILABLE) udp_channel->setName(cmdname); /// first tries a Close of the endpoint. YARPEndpointManager::Close (*udp_channel); /// tests whether a thread termination is required. if (YARPEndpointManager::GetNumberOfClients () < 1) { active = 0; deactivated = 1; } YARPNameService::DeleteName (udp_channel); } break; case 3: { /// disconnect all YARPEndpointManager::CloseMcastAll (); active = 0; deactivated = 1; /// perhaps deactivate = 1; } break; } /// if a message has been processed jump to the end of thread cycle. if (msg_type != 0) { msg_type = 0; PostMutex(); continue; } } /// end of if (protocol_type). /// /// check_tick = YARPTime::GetTimeAsSeconds(); ticking = 1; p_local_sendable.Set(p_sendable.Ptr()); p_sendable.Reset(); PostMutex(); YARP_DBG(THIS_DBG) ((LM_DEBUG, "Waiting for sema to send <<< sema okay!\n")); target_pid->getNameID().setRequireAck(GetRequireAck()); sender.Begin(target_pid->getNameID()); header.tag = MSG_ID_DATA; header.length = 0; header.first = 1; header.more = 0; if (add_header) { sender.Add ((char*)(&header), sizeof(header)); } success = p_local_sendable.Ptr()->Write(sender); if (!success) YARP_DBG(THIS_DBG) ((LM_DEBUG, "*** Fire failed\n")); success = success && sender.End(); WaitMutex(); if (deactivate) { active = 0; deactivated = 1; } if (!success) { YARP_DBG(THIS_DBG) ((LM_DEBUG, "*** Send failed\n")); active = 0; } sending = 0; ticking = 0; PostMutex(); p_local_sendable.Reset(); space_available.Post(); OnSend(); } /// while (!deactivated) if (protocol_type == YARP_MCAST) { YARPEndpointManager::CloseMcastAll (); /// unregister the mcast group. YARPNameService::UnregisterName (target_pid); } else { YARPEndpointManager::Close (*target_pid); } /// but see also what I said on closing the Port thread. YARPNameService::DeleteName(target_pid); ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier())); }
void CAsyncSocketExLayer::CallEvent(int nEvent, int nErrorCode) { if (m_nCriticalError) { return; } m_nCriticalError = nErrorCode; switch (nEvent) { case FD_READ: case FD_FORCEREAD: if (GetLayerState()==connecting && !nErrorCode) { m_nPendingEvents |= nEvent; break; } else if (GetLayerState()==attached) SetLayerState(connected); if (nEvent & FD_READ) m_nPendingEvents &= ~FD_READ; else m_nPendingEvents &= ~FD_FORCEREAD; if (GetLayerState()==connected || nErrorCode) { if (nErrorCode) SetLayerState(aborted); OnReceive(nErrorCode); } break; case FD_WRITE: if (GetLayerState()==connecting && !nErrorCode) { m_nPendingEvents |= nEvent; break; } else if (GetLayerState()==attached) SetLayerState(connected); m_nPendingEvents &= ~FD_WRITE; if (GetLayerState()==connected || nErrorCode) { if (nErrorCode) SetLayerState(aborted); OnSend(nErrorCode); } break; case FD_CONNECT: if (GetLayerState()==connecting || GetLayerState() == attached) { if (!nErrorCode) SetLayerState(connected); else { if (!m_pNextLayer && m_nextAddr) if (TryNextProtocol()) { m_nCriticalError = 0; return; } SetLayerState(aborted); } m_nPendingEvents &= ~FD_CONNECT; OnConnect(nErrorCode); if (!nErrorCode) { if ((m_nPendingEvents & FD_READ) && GetLayerState()==connected) OnReceive(0); if ((m_nPendingEvents & FD_FORCEREAD) && GetLayerState()==connected) OnReceive(0); if ((m_nPendingEvents & FD_WRITE) && GetLayerState()==connected) OnSend(0); } m_nPendingEvents = 0; } break; case FD_ACCEPT: if (GetLayerState()==listening) { if (nErrorCode) SetLayerState(aborted); m_nPendingEvents &= ~FD_ACCEPT; OnAccept(nErrorCode); } break; case FD_CLOSE: if (GetLayerState()==connected || GetLayerState()==attached) { if (nErrorCode) SetLayerState(aborted); else SetLayerState(closed); m_nPendingEvents &= ~FD_CLOSE; OnClose(nErrorCode); } break; } }
void O2Client:: NetIOThread(void) { O2SocketSessionPListIt ssit; int lasterror; while (Active) { // Signal Off SessionListLock.Lock(); { if (sss.empty()) SessionExistSignal.Off(); } SessionListLock.Unlock(); // Wait SessionExistSignal.Wait(); if (!Active) break; // Setup FD fd_set readfds; fd_set writefds; FD_ZERO(&readfds); FD_ZERO(&writefds); SessionListLock.Lock(); { for (ssit = sss.begin(); ssit != sss.end(); ssit++) { O2SocketSession *ss = *ssit; if (ss->can_send) FD_SET(ss->sock, &writefds); if (ss->can_recv) FD_SET(ss->sock, &readfds); } } SessionListLock.Unlock(); // select struct timeval tv; tv.tv_sec = SELECT_TIMEOUT_MS/1000; tv.tv_usec = SELECT_TIMEOUT_MS%1000; select(0, &readfds, &writefds, NULL, &tv); if (!Active) break; // // 既存セッションとの送受信 // SessionListLock.Lock(); ssit = sss.begin(); SessionListLock.Unlock(); while (Active) { bool end = false; SessionListLock.Lock(); { if (ssit == sss.end()) end = true; } SessionListLock.Unlock(); if (end) break; O2SocketSession *ss = *ssit; // IP文字列 wstring ipstr; if (O2DEBUG) ulong2ipstr(ss->ip, ipstr); else ip2e(ss->ip, ipstr); // Send if (FD_ISSET(ss->sock, &writefds)) { int len; const char *buff = ss->GetNextSend(len); if (len > 0) { int n = send(ss->sock, buff, len, 0); if (n > 0) { ss->UpdateSend(n); ss->UpdateTimer(); SendByte += n; OnSend(ss); if (hwndSetIconCallback) { #if defined(_WIN32) && !defined(__WXWINDOWS__) /** Use ordinary windows api */ PostMessage(hwndSetIconCallback, msgSetIconCallback, 1, 0); #else /** Platform is not windows */ #warning "TODO: implement wxWidgets event method here" #endif } } else if (n == 0) { // do nothing } #ifdef _WIN32 /** Windows */ else if ((lasterror = WSAGetLastError()) != WSAEWOULDBLOCK) #else /** Unix */ else if (errno == EAGAIN) #endif { if (Logger) { Logger->AddLog(O2LT_NETERR, ClientName.c_str(), ss->ip, ss->port, L"送信エラー(%d)", lasterror); } ss->error = true; ss->Deactivate(); } } } // Recv if (FD_ISSET(ss->sock, &readfds)) { char buff[RECVBUFFSIZE]; int n = recv(ss->sock, buff, RECVBUFFSIZE, 0); if (n > 0) { ss->AppendRecv(buff, n); ss->UpdateTimer(); RecvByte += n; OnRecv(ss); if (hwndSetIconCallback) { #if defined(_WIN32) && !defined(__WXWINDOWS__) /** Use ordinary windows api */ PostMessage(hwndSetIconCallback, msgSetIconCallback, 0, 0); #else /** Platform is not windows */ #warning "TODO: implement wxWidgets event method here" #endif } } else if (n == 0) { /*if (Logger) { Logger->AddLog(O2LT_NETERR, ClientName.c_str(), ss->ip, ss->port, L"受信0"); }*/ ss->Deactivate(); } #ifdef _WIN32 /** Windows */ else if ((lasterror = WSAGetLastError()) != WSAEWOULDBLOCK) #else /** Unix */ else if (errno == EAGAIN) #endif { if (Logger) { Logger->AddLog(O2LT_NETERR, ClientName.c_str(), ss->ip, ss->port, L"受信エラー(%d)", lasterror); } ss->error = true; ss->Deactivate(); } }