BOOL DoRead(PCLIENT pClient) { SetLastError(NO_ERROR); DWORD nBytes = 0; BOOL b = ReadFile(pClient->hPipe, &pClient->Message, sizeof(pClient->Message), &nBytes, pClient); DWORD error = GetLastError(); if (b && error == NO_ERROR) { return TRUE; } if (error == ERROR_BROKEN_PIPE) { pClient->LogMessageV("<!-- **** ReadFile 002 *** ERROR_BROKEN_PIPE [%d] -->\n", nBytes); CloseConnection(pClient); return TRUE; } else if (error == ERROR_INVALID_HANDLE) { // ? pClient->LogMessageV("<!-- **** ReadFile 002 *** ERROR_INVALID_HANDLE -->\n"); // I have no idea why this happens. Our remedy is to drop the connection. return TRUE; } else if (error != ERROR_IO_PENDING) { if (b) { pClient->LogMessageV("<!-- **** ReadFile 002 succeeded: %d -->\n", error); } else { pClient->LogMessageV("<!-- **** ReadFile 002 failed: %d -->\n", error); } CloseConnection(pClient); } return TRUE; }
NS_IMETHODIMP WebSocket::OnServerClose(nsISupports *aContext, uint16_t aCode, const nsACString &aReason) { NS_ABORT_IF_FALSE(NS_IsMainThread(), "Not running on main thread"); MOZ_ASSERT(mReadyState != WebSocket::CONNECTING, "Received server close before connected?"); MOZ_ASSERT(mReadyState != WebSocket::CLOSED, "Received server close after already closed!"); // store code/string for onclose DOM event mCloseEventCode = aCode; CopyUTF8toUTF16(aReason, mCloseEventReason); if (mReadyState == WebSocket::OPEN) { // Server initiating close. // RFC 6455, 5.5.1: "When sending a Close frame in response, the endpoint // typically echos the status code it received". // But never send certain codes, per section 7.4.1 if (aCode == 1005 || aCode == 1006 || aCode == 1015) { CloseConnection(0, EmptyCString()); } else { CloseConnection(aCode, aReason); } } else { // We initiated close, and server has replied: OnStop does rest of the work. MOZ_ASSERT(mReadyState == WebSocket::CLOSING, "unknown state"); } return NS_OK; }
BOOL CTransmission::OpenConnection() { if (this->isConnected == true && m_pServer != nullptr) { return TRUE; } if (this->m_pListener == nullptr) { return FALSE; } if (m_pServer != nullptr) { CloseConnection(); } this->m_pServer = new CTcpServerPtr(this->m_pListener); if ((*m_pServer) == nullptr) { return FALSE; } ((this->m_pServer)->Get())->SetWorkerThreadCount(1); BOOL state = (*m_pServer)->Start(L"0.0.0.0", 55999); if (state == FALSE) { EnSocketError error = (*m_pServer)->GetLastError(); CloseConnection(); } else { this->isConnected = true; } return state; }
void WebSocketWorker::doRead() { if (!m_isRunning) return; if (!m_webSocketServer.IsRunning() || !m_socket->isOpen()) { CloseConnection(); return; } if (m_webSocketMode) { ProcessFrames(m_socket); } else { if (!ProcessHandshake(m_socket)) SendClose(kCloseProtocolError); } if (!m_webSocketMode) { LOG(VB_HTTP, LOG_WARNING, "WebSocketServer: Timed out waiting for connection upgrade"); CloseConnection(); } }
void UnregisterServer(void) { if (con_state != MSCS_REGISTERED) { con_state = MSCS_NONE; CloseConnection(); return; } con_state = MSCS_NONE; CONS_Printf("Unregistering this server to the master server...\n"); if (MS_Connect(registered_server.ip, registered_server.port, 0)) { CONS_Printf("cannot connect to the master server\n"); return; } if (RemoveFromMasterSever() < 0) CONS_Printf("cannot remove this server from the master server\n"); CloseConnection(); MSCloseUDPSocket(); MSLastPing = 0; }
void FCGXStream::FillBuffer() { if (mFD == INVALID_SOCKET) return; mRecvOut = 0; int amt; do { amt = recv(mFD, (char*)mRecvBuf + mRecvIn, FCGXBUFSIZE - mRecvIn, 0); } while (amt < 0 && #ifdef _WIN32 WSAGetLastError() == WSAEINTR #else errno == EINTR #endif ); if (amt < 0) { LogFatal("FCGXStream::FillBuffer(): Could not read data from socket"); CloseConnection(true); } else if (amt == 0) { LogFatal("Unexpected connection close."); CloseConnection(true); } else { mRecvIn += amt; } }
int ClientNetwork::ReceivePacketNonBlocking( char *recvbuf, unsigned int BufferSize ) { int WriteIndex = 0; int SumRead = 0; int RequiredRead = 0; do{ TRY_MORE_READ_ON_LACK_OF_DATA: // unsigned int Start = GetTimer(); if( WriteIndex == 0 ) iResult = recv( ConnectSocket, &recvbuf[WriteIndex], sizeof( NetworkPacketHeader ), 0 ); else { int SpaceLeftInOurBuffer = BufferSize - WriteIndex; int RemainingToRead = RequiredRead - SumRead; int ActualRead = RemainingToRead; if( ActualRead > SpaceLeftInOurBuffer ) ActualRead = SpaceLeftInOurBuffer; iResult = recv( ConnectSocket, &recvbuf[WriteIndex], ActualRead, 0 ); } if ( iResult == 0 ) { printf( "Connection closed\n" ); CloseConnection(); // exit(1); return iResult; } else if( iResult < 0 ) { int iResult2 = WSAGetLastError(); if( iResult2 == WSAEWOULDBLOCK ) { Sleep( 1 ); printf( "Need more data from server\n" ); goto TRY_MORE_READ_ON_LACK_OF_DATA; // return 0; } printf( "recv failed: %d - %d\n", iResult, iResult2 ); CloseConnection(); // exit(1); return iResult; } if( WriteIndex == 0 ) { NetworkPacketHeader *ph = (NetworkPacketHeader *)recvbuf; RequiredRead = (int)ph->PacketSize; if( (int)BufferSize < RequiredRead ) { assert( false ); return 0; } } WriteIndex += iResult; SumRead += iResult; // unsigned int End = GetTimer(); // printf("network packet fragment size %d, received in %d seconds\n", iResult, End - Start ); }while( SumRead < RequiredRead && BufferSize - WriteIndex > 0 ); return SumRead; }
DWORD WINAPI WorkerThread(LPVOID pvVoid) { PCLIENT pClient; BOOL b; LPOVERLAPPED lpo; DWORD nBytes; HANDLE hCompletionPort = (HANDLE)pvVoid; for (BOOL fKeepLooping = TRUE; fKeepLooping;) { pClient = NULL; lpo = NULL; nBytes = 0; b = GetQueuedCompletionStatus(hCompletionPort, &nBytes, (PULONG_PTR)&pClient, &lpo, INFINITE); if (!b) { if (pClient) { if (GetLastError() == ERROR_BROKEN_PIPE) { pClient->LogMessageV("<!-- Client closed pipe. -->"); } else { pClient->LogMessageV("<!-- *** GetQueuedCompletionStatus failed %d -->", GetLastError()); } CloseConnection(pClient); } continue; } if (pClient->fAwaitingAccept) { BOOL fAgain = TRUE; while (fAgain) { LONG nClient = InterlockedIncrement(&s_nTotalClients); InterlockedIncrement(&s_nActiveClients); pClient->fAwaitingAccept = FALSE; PCLIENT pNew = CreatePipeConnection(hCompletionPort, nClient); fAgain = FALSE; if (pNew != NULL) { fAgain = !pNew->fAwaitingAccept; DoRead(pNew); } } } else { if (nBytes <= offsetof(TBLOG_MESSAGE, szMessage)) { pClient->LogMessageV("</t:Process>\n"); CloseConnection(pClient); continue; } pClient->LogMessage(&pClient->Message, nBytes); } DoRead(pClient); } return 0; }
unsigned __stdcall ClientThread(void *pVoid) { int nRet; BYTE buf[1024]; LPREQUEST lpReq = (LPREQUEST)pVoid; // // Count this client // IncrementClientCount(); // // Recv the request data // if (!RecvRequest(lpReq, buf, sizeof(buf))) { CloseConnection(lpReq); free(lpReq); DecrementClientCount(); return 0; } // // Parse the request info // nRet = ParseRequest(lpReq, buf); if (nRet) { SendError(lpReq, nRet); CloseConnection(lpReq); free(lpReq); DecrementClientCount(); return 0; } // // Send the file to the client // SendFile(lpReq); // // Clean up CloseConnection(lpReq); free(pVoid); // // Subtract this client // DecrementClientCount(); return 0; }
// creates a connection and destroys it again enum TVerdict TE_RConnectionTest301::doTestStepL(void) { TInt err; RConnection activeConn; RConnection conn; RSocketServ ss; TRequestStatus status; TInterfaceNotificationBuf info; err = OpenSocketServer(ss); TESTEL(KErrNone == err, err); CleanupClosePushL(ss); err = OpenConnection(conn, ss); TESTEL(KErrNone == err, err); CleanupClosePushL(conn); err = OpenConnection(activeConn, ss); TESTEL(KErrNone == err, err); CleanupClosePushL(activeConn); err = StartConnectionWithOverrides(conn, 1); TESTEL(KErrNone == err, err); // issue request AllInterfaceNotification(conn, status, info); // start another different connection to complete request if it hasn't already done so err = StartConnectionWithOverrides(activeConn, 6); TESTEL(KErrNone == err, err); // wait for completion User::WaitForRequest(status); // check for correct value TESTEL(status.Int() == KErrInUse, status.Int()); CloseConnection(activeConn); CleanupStack::Pop(); CloseConnection(conn); CleanupStack::Pop(); CloseSocketServer(ss); CleanupStack::Pop(); return TestStepResult(); } // TE_RConnectionTest301
// creates a connection and destroys it again enum TVerdict TE_RConnectionTest304::doTestStepL(void) { TInt err; RSocketServ socketServer; RConnection connection; RConnection monitor; TRequestStatus status; TInterfaceNotificationBuf info; err = OpenSocketServer(socketServer); TESTEL(KErrNone == err, err); CleanupClosePushL(socketServer); err = OpenConnection(connection, socketServer); TESTEL(KErrNone == err, err); CleanupClosePushL(connection); err = OpenConnection(monitor, socketServer); TESTEL(KErrNone == err, err); CleanupClosePushL(monitor); // issue request AllInterfaceNotification(monitor, status, info); // start connection to complete request err = StartConnection(connection); TESTEL(KErrNone == err, err); CheckInterfaceNotificationL(status, info, EInterfaceUp, &connection); // issue request AllInterfaceNotification(monitor, status, info); CloseConnection(connection); CleanupStack::Pop(); CheckInterfaceNotificationL(status, info, EInterfaceDown); CloseConnection(monitor); CleanupStack::Pop(); CloseSocketServer(socketServer); CleanupStack::Pop(); return TestStepResult(); } // TE_RConnectionTest304
int GetUrl(char *url, char **reply_ret, int *len_ret) { char *hostname, *path; int port; XtransConnInfo trans; int status = 0; if (ParseHttpUrl(url, &hostname, &port, &path) != 0) return 1; /* invalid URL */ trans = OpenConnection(hostname, port); if (trans == NULL) { status = 1; /* connection failed */ goto end; } SendGetRequest(trans, path); *len_ret = ReadGetReply(trans, reply_ret); CloseConnection(trans); end: Free(hostname); Free(path); return status; }
// ---------------------------------------------------------------------- void MyServer::slotNewConnection() { // если уже подключено максималное количество пользователей - отсоединяем всех новых if (i>=4) { QTcpSocket* pClientSocket_err = m_ptcpServer->nextPendingConnection(); pClientSocket_err->close(); return; } // если пришел, запрос на подключение и у нас еще есть места для пользователей - создаем сокет для общения с ним // и отправляем ему код для кодирования сообщения QTcpSocket* pClientSocket = m_ptcpServer->nextPendingConnection(); connect(pClientSocket, SIGNAL(disconnected()) , this , SLOT(CloseConnection( pClientSocket))); connect(pClientSocket, SIGNAL(readyRead()), this , SLOT(slotReadClient())); for ( int j = 0; j < 4 ; j++ ) if(clients[i].my_client == NULL) { clients[i].my_client = pClientSocket; clients[i].code = get_cdma_code(); sendToClient_code(&clients[i] ); i++; break; } }
//--------------------------------------------------------------------------- void DagmanClassad::Update( int total, int done, int pre, int submitted, int post, int ready, int failed, int unready, Dag::dag_status dagStatus, bool recovery, const DagmanStats &stats ) { if ( !_valid ) { debug_printf( DEBUG_VERBOSE, "Skipping ClassAd update -- DagmanClassad object is invalid\n" ); return; } Qmgr_connection *queue = OpenConnection(); if ( !queue ) { return; } SetDagAttribute( ATTR_DAG_NODES_TOTAL, total ); SetDagAttribute( ATTR_DAG_NODES_DONE, done ); SetDagAttribute( ATTR_DAG_NODES_PRERUN, pre ); SetDagAttribute( ATTR_DAG_NODES_QUEUED, submitted ); SetDagAttribute( ATTR_DAG_NODES_POSTRUN, post ); SetDagAttribute( ATTR_DAG_NODES_READY, ready ); SetDagAttribute( ATTR_DAG_NODES_FAILED, failed ); SetDagAttribute( ATTR_DAG_NODES_UNREADY, unready ); SetDagAttribute( ATTR_DAG_STATUS, (int)dagStatus ); SetDagAttribute( ATTR_DAG_IN_RECOVERY, recovery ); // Publish DAGMan stats to a classad, then update those also ClassAd stats_ad; stats.Publish( stats_ad ); SetDagAttribute( ATTR_DAG_STATS, stats_ad ); CloseConnection( queue ); }
//--------------------------------------------------------------------------- void DagmanClassad::GetAcctInfo( MyString &group, MyString &user ) { if ( !_valid ) { debug_printf( DEBUG_VERBOSE, "Skipping ClassAd query -- DagmanClassad object is invalid\n" ); return; } Qmgr_connection *queue = OpenConnection(); if ( !queue ) { return; } GetDagAttribute( ATTR_ACCT_GROUP, group, false ); debug_printf( DEBUG_VERBOSE, "Workflow accounting_group: <%s>\n", group.Value() ); GetDagAttribute( ATTR_ACCT_GROUP_USER, user, false ); debug_printf( DEBUG_VERBOSE, "Workflow accounting_group_user: <%s>\n", user.Value() ); CloseConnection( queue ); return; }
const char *GetMODVersion(void) { static msg_t msg; // we must be connected to the master server before writing to it if (MS_Connect(GetMasterServerIP(), GetMasterServerPort(), 0)) { CONS_Printf("cannot connect to the master server\n"); M_StartMessage("There was a problem connecting to\nthe Master Server", NULL, MM_NOTHING); return NULL; } msg.type = GET_VERSION_MSG; msg.length = sizeof MODVERSION; msg.room = MODID; // Might as well use it for something. sprintf(msg.buffer,"%d",MODVERSION); if (MS_Write(&msg) < 0) return NULL; MS_Read(&msg); CloseConnection(); if(strcmp(msg.buffer,"NULL") != 0) { return msg.buffer; } else return NULL; }
void InputImpl::setMousePosition(const Vector2i& position) { // Open a connection with the X server xcb_connection_t* connection = OpenConnection(); ScopedXcbPtr<xcb_generic_error_t> error(xcb_request_check( connection, xcb_warp_pointer( connection, None, // Source window XCBDefaultRootWindow(connection), // Destination window 0, 0, // Source position 0, 0, // Source size position.x, position.y // Destination position ) )); if (error) err() << "Failed to set mouse position" << std::endl; xcb_flush(connection); // Close the connection with the X server CloseConnection(connection); }
void CloseAllConnections(std::vector<SocketServer::Connection*>& clients) { for(std::vector<SocketServer::Connection*>::iterator it = clients.begin(); it != clients.end(); ++it ) { CloseConnection(*it); delete *it; } clients.clear(); }
void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); }
void MainQuit(HWND hwnd) { CloseConnection(); if (config.save_settings) SaveSettings(); FreeProfaneTerms(); MainExitState(); FontsDestroy(); ColorsDestroy(); MusicClose(); PaletteDeactivate(); DeleteObject(hPal); HookClose(); FreeLibrary(hRichEditLib); D3DRenderShutDown(); PostQuitMessage(0); }
static INT32 ConnectionFailed(void) { con_state = MSCS_FAILED; CONS_Printf("Connection to master server failed\n"); CloseConnection(); return MS_CONNECT_ERROR; }
//------------------------------------------------------------------------------------------------------------------------------------------------------ err_t CallbackOnPoll(void *_arg, struct tcp_pcb *_tpcb) { err_t ret_err; struct State *ss = (struct State *)_arg; if (ss != NULL) { if (ss->p != NULL) { // there is a remaining pbuf (chain) //tcp_sent(_tpcb, CallbackOnSent); Send(_tpcb, ss); } else { // no remaining pbuf (chain) if (ss->state == S_CLOSING) { CloseConnection(_tpcb, ss); } } ret_err = ERR_OK; } else { // nothing to be done tcp_abort(_tpcb); ret_err = ERR_ABRT; } return ret_err; }
int Net::Receive(void* c, msglen_t size, long int useconds) { if (s > 0) { struct timeval tv; fd_set rfd; tv.tv_sec = 0; tv.tv_usec = useconds; FD_ZERO(&rfd); FD_SET(s, &rfd); memset(c, 0, size); switch (select(1 + s, &rfd, 0, 0, &tv)) { case -1: std::cerr << "select error" << std::endl; return -1; break; case 0: return 0; break; default: if (FD_ISSET(s, &rfd)) { int size_read = recv(s, c, sizeof(msglen_t), 0); msglen_t msg_len = *((msglen_t*) c); size_read = recv(s, c, msg_len, 0); if (size_read < 1) { CloseConnection(); return -1; } return size_read; } break; } } return 0; }
//////////////////////////// // DTOR AltaF::~AltaF() { // trying to leave the camera in a good imaging state // from Ticket #111 in the Alta project and ticket #87 in Zenith if( m_IsConnected ) { try { CloseConnection(); } catch( std::exception & err ) { std::string msg ("Exception caught in ~AltaF msg = " ); msg.append( err.what() ); ApgLogger::Instance().Write(ApgLogger::LEVEL_RELEASE,"error", msg); } catch( ... ) { ApgLogger::Instance().Write(ApgLogger::LEVEL_RELEASE,"error", "Unknown exception caught stopping exposure in ~AltaF" ); } } }
//--------------------------------------------------------------------------- void DagmanClassad::GetSetBatchName( const MyString &primaryDagFile, MyString &batchName ) { if ( !_valid ) { debug_printf( DEBUG_VERBOSE, "Skipping ClassAd query -- DagmanClassad object is invalid\n" ); return; } Qmgr_connection *queue = OpenConnection(); if ( !queue ) { return; } if ( !GetDagAttribute( ATTR_JOB_BATCH_NAME, batchName, false ) ) { // Default batch name is top-level DAG's primary // DAG file (base name only). batchName = condor_basename( primaryDagFile.Value() ); batchName += "+"; batchName += IntToStr( _dagmanId._cluster ); SetDagAttribute( ATTR_JOB_BATCH_NAME, batchName ); } CloseConnection( queue ); debug_printf( DEBUG_VERBOSE, "Workflow batch-name: <%s>\n", batchName.Value() ); }
void Network::DeInit() { LOG(LogVerbose, "Network::DeInit: Closing down."); PolledTimer timer; // Kill all connections. while(connections.size() > 0) { MessageConnection *connection = *connections.begin(); CloseConnection(connection); // CloseConnection erases connection from the connections list, so this loop terminates. } // Kill the server, if it's running. StopServer(); // Kill all worker threads. while(workerThreads.size() > 0) CloseWorkerThread(workerThreads.front()); // Erases the item from workerThreads, so this loop terminates. // Clean up any sockets that might be remaining. while(sockets.size() > 0) { sockets.front().Close(); sockets.pop_front(); } // Deinitialize network subsystem. #ifdef WIN32 WSACleanup(); #endif LOG(LogWaits, "Network::DeInit: Deinitialized kNet Network object, took %f msecs.", timer.MSecsElapsed()); }
Vector2i InputImpl::getMousePosition() { // Open a connection with the X server xcb_connection_t* connection = OpenConnection(); ScopedXcbPtr<xcb_generic_error_t> error(NULL); ScopedXcbPtr<xcb_query_pointer_reply_t> pointer( xcb_query_pointer_reply( connection, xcb_query_pointer( connection, XCBDefaultRootWindow(connection) ), &error ) ); // Close the connection with the X server CloseConnection(connection); if (error) { err() << "Failed to query pointer" << std::endl; return Vector2i(0, 0); } return Vector2i(pointer->root_x, pointer->root_y); }
void CMQTTClient::Unsubscribe (const char *pTopic) { assert (pTopic != 0); u16 usPacketIdentifier = m_usNextPacketIdentifier; if (++m_usNextPacketIdentifier == 0) { m_usNextPacketIdentifier++; } CMQTTSendPacket *pPacket = new CMQTTSendPacket (MQTTUnsubscribe, m_nMaxPacketSize); assert (pPacket != 0); pPacket->AppendWord (usPacketIdentifier); pPacket->AppendString (pTopic); if (!SendPacket (pPacket)) { delete pPacket; CloseConnection (MQTTDisconnectSendFailed); return; } pPacket->SetQoS (MQTT_QOS_AT_LEAST_ONCE); pPacket->SetPacketIdentifier (usPacketIdentifier); InsertPacketIntoQueue (pPacket, m_pTimer->GetTicks () + MQTT_RESEND_TIMEOUT); }
void InputImpl::setMousePosition(const Vector2i& position, const Window& relativeTo) { // Open a connection with the X server xcb_connection_t* connection = OpenConnection(); WindowHandle handle = relativeTo.getSystemHandle(); if (handle) { ScopedXcbPtr<xcb_generic_error_t> error(xcb_request_check( connection, xcb_warp_pointer( connection, None, // Source window handle, // Destination window 0, 0, // Source position 0, 0, // Source size position.x, position.y // Destination position ) )); if (error) err() << "Failed to set mouse position" << std::endl; xcb_flush(connection); } // Close the connection with the X server CloseConnection(connection); }
//--------------------------------------------------------------------------- void DagmanClassad::GetInfo( MyString &owner, MyString &nodeName ) { if ( !_valid ) { debug_printf( DEBUG_VERBOSE, "Skipping ClassAd query -- DagmanClassad object is invalid\n" ); return; } Qmgr_connection *queue = OpenConnection(); if ( !queue ) { return; } if ( !GetDagAttribute( ATTR_OWNER, owner ) ) { check_warning_strictness( DAG_STRICT_1 ); owner = "undef"; } if ( !GetDagAttribute( ATTR_DAG_NODE_NAME, nodeName ) ) { // We should only get this value if we're a sub-DAG. nodeName = "undef"; } CloseConnection( queue ); return; }