bool TcpClient::Connect_() { int fd; sockaddr_in sock_addr; fd = socket(AF_INET, SOCK_STREAM, 0); sock_addr.sin_family = PF_INET; sock_addr.sin_port = htons(server_addr_.port_); inet_aton(server_addr_.ip_.c_str(), &sock_addr.sin_addr); int reuseaddr = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)) == -1) { OnError(errno, strerror(errno)); close(fd); return false; } if (connect(fd, (sockaddr*)&sock_addr, sizeof(sockaddr_in)) == -1) { OnError(errno, strerror(errno)); close(fd); return false; } IPAddress local_addr; SocketAddrToIPAddress(sock_addr, local_addr); OnConnected(fd, local_addr); return true; }
void ClientConnection::Update(float deltaTime) { // This is for local communications mode (non networked mode) if (localCommunications_) { // Send the OnConnected event if this is the first time we Update after a Connect if (!localCommunications_OnConnected_Done_) { OnConnected(); localCommunications_OnConnected_Done_=true; } // Process all messages in the buffer if (localClientCommunicationsBuffer_) { localClientCommunicationsBuffer_->SetPosition(0); while (localClientCommunicationsBuffer_->GetPosition()<localClientCommunicationsBuffer_->GetSize()) { int size=0; localClientCommunicationsBuffer_->Read(&size); OnReceiveData(StaticBuffer(static_cast<unsigned char*>(localClientCommunicationsBuffer_->GetPointer())+localClientCommunicationsBuffer_->GetPosition(),size)); localClientCommunicationsBuffer_->SetPosition(localClientCommunicationsBuffer_->GetPosition()+size); } localClientCommunicationsBuffer_->Clear(false); } } }
bool ZBirdDummyClient::OnSockRecv(SOCKET sock, char* pPacket, DWORD dwSize) { if (m_pCommandBuilder==NULL) return false; // New Cmd Buffer //////////////// m_pCommandBuilder->SetUID(m_This, GetSenderUIDBySocket(sock)); m_pCommandBuilder->Read((char*)pPacket, dwSize); LockRecv(); while(MCommand* pCmd = m_pCommandBuilder->GetCommand()) { Post(pCmd); } UnlockRecv(); while(MPacketHeader* pNetCmd = m_pCommandBuilder->GetNetCommand()) { if (pNetCmd->nMsg == MSGID_REPLYCONNECT) { MReplyConnectMsg* pMsg = (MReplyConnectMsg*)pNetCmd; MUID HostUID, AllocUID; HostUID.High = pMsg->nHostHigh; HostUID.Low = pMsg->nHostLow; AllocUID.High = pMsg->nAllocHigh; AllocUID.Low = pMsg->nAllocLow; free(pNetCmd); LockRecv(); OnConnected(sock, &HostUID, &AllocUID); UnlockRecv(); } } return true; }
void Client::Connected() { if (_connected) return; _connected = true; OnConnected(); }
//--------------------------------------------------------------------------------------- tThreadClient::tThreadClient(const int _handle, QSqlDatabase &_db):my_thread(NULL),this_client(NULL) { my_thread= new QThread(); this->moveToThread(my_thread); this_client=new tClient(_handle, _db); this_client->moveToThread(my_thread); connect(this_client, SIGNAL(DisconnectClient(int)), this, SLOT(OnDisconnectClient(int))); connect(this, SIGNAL(ConnectClient()), this_client, SLOT(OnConnected())); }
void NET_Client::PrivateOnConnected() { // MutexWrap socket_access(m_socket_mutex); m_connecting = false; m_connected = true; m_read_thread.Start(THREAD_PRIORITY_NORMAL); m_write_thread.Start(THREAD_PRIORITY_NORMAL); OnConnected(); }
Irc::Irc(const char* host, int port) { m_host = host; m_port = port; m_connected = false; m_message_queue = new MessageQueue(&m_socket); //connect signals connect(&m_socket, SIGNAL(connected()), this, SLOT(OnConnected())); connect(&m_socket, SIGNAL(disconnected()), this, SLOT(OnDisconnected())); }
int CCSocketHandler::Connect(){ int ret = -1; if (_stage == CONN_IDLE){ ret = CNet::tcp_connect(&netfd, GetSIP().c_str(), GetPort(), 0,500); log_debug("Connect..."); } else { if (netfd < 0) { ret = CNet::tcp_connect(&netfd, GetSIP().c_str(), GetPort(), 0,500); } else { ret = 1; } } if(ret <0) { /* if (ret == SOCKET_CREATE_FAILED) { log_error("*STEP: helper create socket failed, errno[%d], msg[%s]", errno, strerror(errno)); return -1; } if(errno != EINPROGRESS) { log_error("*STEP: PROXY connect to logic failed, errno[%d], msg[%s]", errno , strerror(errno)); return -1; } _stage = CONN_CONNECTING; log_debug("*STEP: PROXY connecting to logic, unix fd[%d]", netfd); goto exit;*/ if( netfd > 0) { close(netfd); } return -1; } else if( 0 == ret) { _stage = CONN_CONNECTED; OnConnected(); } //exit: return CCReactor::Instance()->AttachPoller(this); }
void WorldConnection::Process() { //persistent connection.... if (!Connected()) { pConnected = tcpc.Connected(); if (pConnected) { OnConnected(); } else return; } }
ClientConnection* GameServer::CreateClientConnection(ConnectedSocketInfo* pSockInfo, SocketServer* pSockServer){ if( !pSockInfo ) return NULL; ClientConnection* pConnNew = new ClientConnection(pSockInfo, this, pSockInfo->m_pSockConn, pSockServer); m_lockConnections.Lock(); // Lock pConnNew = (ClientConnection*)SafePointer::Retain(pConnNew); // Retain connection pointer. m_arrAcceptedSocks.Add((void*)pSockInfo->m_sock, (void*)pConnNew); m_lockConnections.Unlock(); // Unlock OnConnected(pConnNew, pSockInfo); return pConnNew; }
void TCPConnection::Start() { LOG_DEBUG(Formatter::Format("TCP connection started for session {0}", session_id_)); connection_state_ = StateConnected; OnConnected(); if (connection_security_ == CSSSL) { EnqueueHandshake(); } }
void AOnlineBeaconClient::ClientOnConnected_Implementation() { SetConnectionState(EBeaconConnectionState::Open); BeaconConnection->State = USOCK_Open; Role = ROLE_Authority; SetReplicates(true); SetAutonomousProxy(true); // Fail safe for connection to server but no client connection RPC GetWorldTimerManager().ClearTimer(TimerHandle_OnFailure); // Call the overloaded function for this client class OnConnected(); }
bool CNetwork_Asio::Connect() { tcp::resolver resolver(*networkService_->Get_IO_Service()); auto endpoint_iterator = resolver.resolve(network_ip_address, std::to_string(network_port_)); OnConnect(); asio::async_connect( socket_, endpoint_iterator, [this](std::error_code errorCode, const asio::ip::tcp::endpoint) { if (!errorCode) { OnConnected(); } }); active_ = true; return true; }
BOOL CDownloadTransferED2K::RunQueued(DWORD tNow) { ASSERT( m_pClient != NULL ); ASSERT( m_nState == dtsQueued ); if ( Settings.Downloads.QueueLimit > 0 && m_nQueuePos > Settings.Downloads.QueueLimit ) { theApp.Message( MSG_ERROR, IDS_DOWNLOAD_QUEUE_HUGE, (LPCTSTR)m_sAddress, (LPCTSTR)m_pDownload->GetDisplayName(), m_nQueuePos ); Close( TRI_FALSE ); return FALSE; } else if ( m_pClient->m_bConnected == FALSE && tNow > m_tRanking && tNow - m_tRanking > Settings.eDonkey.ReAskTime * 1000 + 20000 ) { theApp.Message( MSG_ERROR, IDS_DOWNLOAD_QUEUE_TIMEOUT, (LPCTSTR)m_sAddress, (LPCTSTR)m_pDownload->GetDisplayName() ); Close( TRI_UNKNOWN ); return FALSE; } else if ( !( CEDPacket::IsLowID( m_pSource->m_pAddress.S_un.S_addr ) || m_pSource->m_bPushOnly ) && /*!Network.IsFirewalled(CHECK_BOTH)*/!Network.IsFirewalled(CHECK_UDP) && m_pClient->m_nUDP > 0 && ! m_bUDP && tNow > m_tRequest && // Temp disable tNow - m_tRequest > Settings.eDonkey.ReAskTime * 1000 - 20000 ) { CEDPacket* pPing = CEDPacket::New( ED2K_C2C_UDP_REASKFILEPING, ED2K_PROTOCOL_EMULE ); pPing->Write( m_pDownload->m_oED2K ); Datagrams.Send( &m_pClient->m_pHost.sin_addr, m_pClient->m_nUDP, pPing ); m_bUDP = TRUE; //m_tRequest = GetTickCount(); } else if ( tNow > m_tRequest && tNow - m_tRequest > Settings.eDonkey.ReAskTime * 1000 ) { m_tRequest = GetTickCount(); if ( m_pClient->IsOnline() ) { return OnConnected(); } else { m_pClient->Connect(); } } return TRUE; }
void XSocketImpl::OnReceiveMessage(const MessageConstPtr& msg) { byte packetID = msg->GetMessageID(); // If this is a user's packet, forward it to them if (packetID >= ID_USER_PACKET_ENUM) { if (m_listener) { m_listener->OnMessageReceived(this, msg->GetData(), msg->GetSize()); } else { LogError("XSocket received message with no listener"); } } else { // Check to see if this is a packet we should handle (connected, disconnected, etc) switch (packetID) { case ID_CONNECTION_REQUEST_ACCEPTED: OnConnected(); break; case ID_DISCONNECTION_NOTIFICATION: OnLostConnection(); break; case ID_CONNECTION_LOST: OnLostConnection(); break; case ID_CONNECTION_ATTEMPT_FAILED: case ID_ALREADY_CONNECTED: case ID_NO_FREE_INCOMING_CONNECTIONS: OnConnectionAttemptFailed(packetID); break; case ID_IP_RECENTLY_CONNECTED: LogInfo("Connection attempt rejected because it was too soon after the last connection"); break; } } }
int OnSocketEvent(const int fd, const NF_NET_EVENT eEvent, NFINet* pNet) { if (eEvent & BEV_EVENT_CONNECTED) { OnConnected(fd, pNet); } else { OnDisConnected(fd, pNet); } if (mEventCB) { mEventCB(fd, eEvent, pNet); } return 0; }
nsresult ConnectionOrientedSocketIO::Accept(int aFd, const struct sockaddr* aPeerAddress, socklen_t aPeerAddressLength) { MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop()); MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_CONNECTING); SetSocket(aFd, SOCKET_IS_CONNECTED); // Address setup mPeerAddressLength = aPeerAddressLength; memcpy(&mPeerAddress, aPeerAddress, mPeerAddressLength); // Signal success and start data transfer OnConnected(); return NS_OK; }
void ZKAgent::OnWatch(int type, int state, const char *path) { if (type == ZOO_SESSION_EVENT) { if (state == ZOO_CONNECTED_STATE) { OnConnected(); } else if (state == ZOO_AUTH_FAILED_STATE) { OnAuthFailed(); } else if (state == ZOO_EXPIRED_SESSION_STATE) { OnSessionExpired(); } else if (state == ZOO_CONNECTING_STATE) { } } }
void AOnlineBeaconClient::ClientOnConnected_Implementation() { Role = ROLE_Authority; SetReplicates(true); SetAutonomousProxy(true); // Fail safe for connection to server but no client connection RPC GetWorldTimerManager().ClearTimer(TimerHandle_OnFailure); if (NetDriver) { // Increase timeout while we are connected NetDriver->InitialConnectTimeout = BeaconConnectionTimeout; NetDriver->ConnectionTimeout = BeaconConnectionTimeout; } // Call the overloaded function for this client class OnConnected(); }
void IOCPServer::OnTick() { //server block until new client connected. SOCKET acceptedSocket = accept(tcpListenSocket_, NULL, NULL); if (acceptedSocket == INVALID_SOCKET) { return; } auto client = ClientManager::Get()->CreateClient(acceptedSocket); if (client != nullptr) { if (!client->OnConnected(acceptedSocket)) { client->Disconnect(); } } ClientManager::Get()->FlushClientSend(); }
bool CGateConnector::Connect() { int iRet = 0; for (int i = 0; i < DEF_MAXGATESOCKET; i++) { Sockets[i] = new NetSock; if (Sockets[i]->Connect(GameServer::getInstance().GateServerAddr.c_str(), GameServer::getInstance().GateServerPort)) { GameServer::getInstance().PutLog("(*) Connection-" + toString<int> (i) + " established!"); iRet += 1; OnConnected(i); } else { GameServer::getInstance().PutLog("(!) Failed on connection-" + toString<int> (i)); delete Sockets[i]; Sockets[i] = NULL; } } return iRet == DEF_MAXGATESOCKET; }
bool NetworkConnection::openConnection(const QString & host, const unsigned short port, bool not_main_connection) { qsocket = new QTcpSocket(); //try with no parent passed for now if(!qsocket) return 0; //connect signals //connect(qsocket, SIGNAL(hostFound()), SLOT(OnHostFound())); connect(qsocket, SIGNAL(connected()), SLOT(OnConnected())); connect(qsocket, SIGNAL(readyRead()), SLOT(OnReadyRead())); connect(qsocket, SIGNAL(disconnected ()), SLOT(OnConnectionClosed())); // connect(qsocket, SIGNAL(delayedCloseFinished()), SLOT(OnDelayedCloseFinish())); // connect(qsocket, SIGNAL(bytesWritten(qint64)), SLOT(OnBytesWritten(qint64))); connect(qsocket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(OnError(QAbstractSocket::SocketError))); if(qsocket->state() != QTcpSocket::UnconnectedState) { qDebug("Called openConnection while in state %d", qsocket->isValid()); return 0; } //remove asserts later Q_ASSERT(host != 0); Q_ASSERT(port != 0); if(!not_main_connection) drawPleaseWait(); qDebug("Connecting to %s %d...\n", host.toLatin1().constData(), port); // assume info.host is clean qsocket->connectToHost(host, (quint16) port); /* If dispatch does not have a UI, the thing that sets the UI * will setupRoomAndConsole */ /* Tricky now without dispatches... who sets up the UI? * there's always a mainwindow... but maybe things aren't setup? */ /* connectionInfo as a message with those pointers is probably a bad idea */ return (qsocket->state() != QTcpSocket::UnconnectedState); }
BOOL CConnection::OnRun() { if ( INVALID_SOCKET == m_hSocket ) return FALSE; WSANETWORKEVENTS pEvents; WSAEnumNetworkEvents( m_hSocket, NULL, &pEvents ); if ( pEvents.lNetworkEvents & FD_CONNECT ) { if ( pEvents.iErrorCode[ FD_CONNECT_BIT ] != 0 ) { OnDropped( TRUE ); return FALSE; } if ( ! OnConnected() ) return FALSE; } BOOL bClosed = ( pEvents.lNetworkEvents & FD_CLOSE ) ? TRUE : FALSE; // if ( pEvents.lNetworkEvents & FD_WRITE ) { if ( ! OnWrite() ) return FALSE; } // if ( pEvents.lNetworkEvents & FD_READ ) { if ( ! OnRead() ) return FALSE; } if ( bClosed ) { OnDropped( pEvents.iErrorCode[ FD_CLOSE_BIT ] != 0 ); return FALSE; } return TRUE; }
void HandleEvent(EventType et, int errornum = 0) { switch (et) { case EVENT_READ: /* fd readable event, received ident response */ ReadResponse(); break; case EVENT_WRITE: /* fd writeable event, successfully connected! */ OnConnected(); break; case EVENT_ERROR: /* fd error event, ohshi- */ ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "EVENT_ERROR"); /* We *must* Close() here immediately or we get a * huge storm of EVENT_ERROR events! */ Close(); done = true; break; } }
nsresult BluetoothDaemonConnectionIO::Accept(int aFd, const union sockaddr_any* aAddr, socklen_t aAddrLen) { MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop()); MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_CONNECTING); // File-descriptor setup if (TEMP_FAILURE_RETRY(fcntl(aFd, F_SETFL, O_NONBLOCK)) < 0) { OnError("fcntl", errno); ScopedClose cleanupFd(aFd); return NS_ERROR_FAILURE; } SetSocket(aFd, SOCKET_IS_CONNECTED); // Signal success OnConnected(); return NS_OK; }
void NetSocket::OnCompletionSuccess(NetCompletionOP* bufObj, DWORD bytesTransfered) { REFLIB_ASSERT_RETURN_IF_FAILED(bufObj, "OnCOmpletionFailure: NetCompletionOP is nullptr."); switch (bufObj->op) { case NetCompletionOP::OP_CONNECT: OnConnected(); break; case NetCompletionOP::OP_READ: OnRecv(bufObj, bytesTransfered); break; case NetCompletionOP::OP_WRITE: OnSent(bufObj, bytesTransfered); break; case NetCompletionOP::OP_DISCONNECT: OnDisconnected(); break; default: REFLIB_ASSERT(false, "Invalid net op"); break; } }
nsresult UnixSocketWatcher::Connect(const struct sockaddr* aAddr, socklen_t aAddrLen) { MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop()); MOZ_ASSERT(IsOpen()); MOZ_ASSERT(aAddr || !aAddrLen); if (connect(GetFd(), aAddr, aAddrLen) < 0) { if (errno == EINPROGRESS) { mConnectionStatus = SOCKET_IS_CONNECTING; // Set up a write watch to receive the connect signal AddWatchers(WRITE_WATCHER, false); } else { OnError("connect", errno); } return NS_ERROR_FAILURE; } mConnectionStatus = SOCKET_IS_CONNECTED; OnConnected(); return NS_OK; }
void PipeStream::OnCustomCompleted(HandleStream::AsyncContext* async_context, HRESULT result, ULONG_PTR length) { auto context = static_cast<AsyncContext*>(async_context); auto listener = static_cast<Listener*>( static_cast<HandleStream::Listener*>(context->listener)); switch (context->type) { case PipeRequest::WaitForConnection: if (HRESULT_CODE(result) == ERROR_PIPE_CONNECTED) result = S_OK; listener->OnConnected(this, result); break; case PipeRequest::Transact: listener->OnTransacted(this, result, length); break; default: assert(false); } }
void UnixSocketWatcher::OnFileCanWriteWithoutBlocking(int aFd) { MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop()); MOZ_ASSERT(aFd == GetFd()); if (mConnectionStatus == SOCKET_IS_CONNECTED) { OnSocketCanSendWithoutBlocking(); } else if (mConnectionStatus == SOCKET_IS_CONNECTING) { RemoveWatchers(WRITE_WATCHER); int error = 0; socklen_t len = sizeof(error); if (getsockopt(GetFd(), SOL_SOCKET, SO_ERROR, &error, &len) < 0) { OnError("getsockopt", errno); } else if (error) { OnError("connect", error); } else { mConnectionStatus = SOCKET_IS_CONNECTED; OnConnected(); } } else { NS_NOTREACHED("invalid connection state for writing"); } }
//-------------------------------------------------------------------------------- bool CPipeConnector::Connect() { _WINQ_FCONTEXT( "CPipeConnector::Connect" ); unsigned long ulError = 0; CTime Time; unsigned long ulInitialTickCount = Time.GetTickCount(); do { m_bConnected = m_Pipe.Open( m_strServerName, m_strPipeName, m_ulAccess, m_ulShareMode, m_pSecurity, m_ulFlags ); if( !m_bConnected ) { ulError = m_ErrorHelper.GetLastError(); } }while( !m_bConnected && ( ulError == nsWin32::ErrorPipeBusy ) && ( ( Time.GetTickCount() - ulInitialTickCount ) < m_ulConnectionTimeout ) ); if( !AsyncConnection() ) { m_bConnected ? OnConnected() : OnConnectionError(); } return m_bConnected; }