// This demonstrates how to perform a graceful disconnect, where data sending/receiving // is allowed to complete before the client is disconnected. // In this demo the server begins the graceful disconnect process // It is also possible for a client to initiate a graceful disconnect #include #include #include #include using namespace std; // Entry point void main() { // Connect to server int iReturn = 0; cout << "DarkNet version: " << mnGetVersion() << "\n"; long long int RecvPacket = mnCreatePacket(); long long int SendPacket = mnCreatePacket(); mnSetMemorySize(SendPacket,1024); mnStart(1,0); mnDisableUDP(0); mnEnableGracefulDisconnect(0); iReturn = mnConnect(0,"127.0.0.1",6565,0,0,5,true); switch(iReturn) { case(1): cout << "Connected to server\n"; break; case(0): cout << "Connection timed out\n"; system("PAUSE"); return; break; case(-1): cout << "An unknown error occurred whilst trying to connect\n"; system("PAUSE"); return; break; case(-2): cout << "The connection request was rejected because the server is full\n"; system("PAUSE"); return; break; } // Main loop unsigned int SendTimer = 0; unsigned int SendFreq = 2000; int iClientStatus; do { // Use less CPU Sleep(1); iClientStatus = mnClientConnected(0,0); switch(iClientStatus) { // Server has begun to gracefully disconnect us // No further data can be received but we can use // what has already been received, and is stored in // the packet queue case(C_NO_RECV): cout << "mnClientConnected: " << iClientStatus << "\n"; // Deal with data received and in packet queue while(mnRecvTCP(0,RecvPacket,0) > 0) { cout << "Final TCP data received\n"; } // Send final data // When mnSendTCP returns data has been sent // and so cleanup after this will NOT cause the // send to fail mnAddStringC(SendPacket,"Goodbye server, I will miss you!\n",0,true); mnSendTCP(0,SendPacket,0,false,true); // Shutdown // No further data can be sent // mnClientConnected will use mnDisconnectClient/mnFinish // to clean up the instance and will return 0, completing // the disconnect process mnShutdownClient(0,0); cout << "Received all data, sent final message to server and fully disconnected\n"; break; } if(iClientStatus == C_CONNECTED) { // TCP packets iReturn = mnRecvTCP(0,RecvPacket,0); if(iReturn > 0) { cout << "New TCP packet received\n"; } // Send messages every SendFreq ms if(clock() - SendTimer > SendFreq) { time_t time1 = time(NULL); tm * time2 = localtime(&time1); char * str = asctime(time2); mnAddStringC(SendPacket,str,0,true); cout << "String sent to server: " << str; // Send packet mnSendTCP(0,SendPacket,0,0,1); // Update timer SendTimer = clock(); } } }while(iClientStatus != C_NOT_CONNECTED); // Cleanup and exit cout << "\n\nDisconnected from server!\n"; system("PAUSE"); mnFinish(-1); }