Exemplo n.º 1
0
void wifi_http()
{
    TCPSocket socket;
    int ret;

    ret = get_wifi()->connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
    TEST_ASSERT_MESSAGE(ret == 0, "Connect failed");

    // Open a socket on the network interface, and create a TCP connection to www.arm.com
    ret = socket.open(get_wifi());
    TEST_ASSERT_MESSAGE(ret == 0, "Socket open failed");
    ret = socket.connect("www.arm.com", 80);
    TEST_ASSERT_MESSAGE(ret == 0, "Socket connect failed");

    // Send a simple http request
    char sbuffer[] = "GET / HTTP/1.1\r\nHost: www.arm.com\r\n\r\n";
    int scount = socket.send(sbuffer, sizeof sbuffer);
    TEST_ASSERT_MESSAGE(scount >= 0, "Socket send failed");

    // Recieve a simple http response and check if it's not empty
    char rbuffer[64];
    int rcount = socket.recv(rbuffer, sizeof rbuffer);
    TEST_ASSERT_MESSAGE(rcount >= 0, "Socket recv error");
    TEST_ASSERT_MESSAGE(rcount > 0, "No data received");

    ret = socket.close();
    TEST_ASSERT_MESSAGE(ret == 0, "Socket close failed");

    ret = get_wifi()->disconnect();
    TEST_ASSERT_MESSAGE(ret == 0, "Disconnect failed");
}
Exemplo n.º 2
0
bool Init()
{
    cout << "connecting to TCP " << gHost << ":" << gPort << " unum " << unum << "\n";

    try
        {
            Addr local(INADDR_ANY,INADDR_ANY);
            gSocket.bind(local);
        }

    catch (BindErr error)
        {
            cerr << "failed to bind socket with '"
                 << error.what() << "'" << endl;

            gSocket.close();
            return false;
        }

    try
        {
            Addr server(gPort,gHost);
            gSocket.connect(server);
        }

    catch (ConnectErr error)
        {
            cerr << "connection failed with: '"
                 << error.what() << "'" << endl;
            gSocket.close();
            return false;
        }

    return true;
}
Exemplo n.º 3
0
static void _tcpsocket_connect_to_chargen_srv(TCPSocket& sock) {
    SocketAddress tcp_addr;

    get_interface()->gethostbyname(MBED_CONF_APP_ECHO_SERVER_ADDR, &tcp_addr);
    tcp_addr.set_port(19);

    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.open(get_interface()));
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.connect(tcp_addr));
}
Exemplo n.º 4
0
bool Email::sendEmail( const std::string &smtpServer, u16 port, const std::string &from, const std::string &to, const std::string &subject, const std::string &body, const std::string &attachedFile /*= ""*/, bool onlyCheck /*= false */ )
{
    bool ok = false;
    TCPSocket sock;
    Address ad(smtpServer, port);
    sock.connect(ad);
    if (sock.connected())
    {
        // we must skip the first line
        std::string formatedBody = "\r\n";
        if(!sendEMailCommand (sock, "", 220)) goto end;
        if(onlyCheck)
        {
            if(!sendEMailCommand (sock, "HELO localhost")) goto end;
            if(!sendEMailCommand (sock, "MAIL FROM: " + from)) goto end;
            if(!sendEMailCommand (sock, "RCPT TO: " + to)) goto end;
            if(!sendEMailCommand (sock, "QUIT", 221)) goto end;

            ok = true;
        }
        else
        {
            if(!sendEMailCommand (sock, "HELO localhost")) goto end;
            //if(!sendEMailCommand (sock, "STARTTLS", 220)) goto end;
            //if(!sendEMailCommand (sock, "AUTH PLAIN AHVzZXIAc2VjcmV0")) goto end;
            if(!sendEMailCommand (sock, "AUTH LOGIN", 334)) goto end;
            if(!sendEMailCommand (sock, "bccr001")) goto end;
            if(!sendEMailCommand (sock, "MAIL FROM: " + from)) goto end;
            if(!sendEMailCommand (sock, "RCPT TO: " + to)) goto end;
            if(!sendEMailCommand (sock, "DATA", 354)) goto end;

            std::string buffer =
                "From: " + from + "\r\n"
                "To: " + to + "\r\n"
                "Subject: " + subject + "\r\n"
                + formatedBody + "\r\n.";

            if(!sendEMailCommand (sock, buffer)) goto end;
            if(!sendEMailCommand (sock, "QUIT", 221)) goto end;

            ok = true;
        }
end:
        sock.close();
    }
    else
    {
        MessageBox(NULL, smtpServer.c_str(), "woops", MB_OK);
    }
    return ok;
}
Exemplo n.º 5
0
static nsapi_error_t _tcpsocket_connect_to_chargen_srv(TCPSocket &sock)
{
    SocketAddress tcp_addr;

    get_interface()->gethostbyname(MBED_CONF_APP_ECHO_SERVER_ADDR, &tcp_addr);
    tcp_addr.set_port(19);

    nsapi_error_t err = sock.open(get_interface());
    if (err != NSAPI_ERROR_OK) {
        return err;
    }

    return sock.connect(tcp_addr);
}
int main() {

	TCPSocket socket;
	socket.connect("169.254.0.10", 10001);

	boost::thread requisicoes1(fazRequisicoes, &socket, "8", .2);
	boost::thread requisicoes2(fazRequisicoes, &socket, "5", .2);
	boost::thread requisicoes3(fazRequisicoes, &socket, "I", 1);
	boost::thread leitura(recebeRequisicoes, &socket);

	while(1);

	printf("finalizou a thread principal\n");

	return 0;
}
Exemplo n.º 7
0
    TCPSocket*
    Session::openDataConnection(void)
    {
      TCPSocket* sock = NULL;

      if (m_data_pasv)
      {
        sock = m_sock_data->accept();
      }
      else
      {
        sock = new TCPSocket;
        sock->connect(m_data_addr, m_data_port);
        sock->setKeepAlive(true);
      }

      return sock;
    }
Exemplo n.º 8
0
void MasterQuery::refresh() throw (MasterQueryException) {
    TCPSocket query;
    char buffer[1024];
    std::string pending;

    try {
        query.connect(masterserver.c_str(), masterport);
        while (query.is_connected()) {
            if (query.activity(0, 100000)) {
                memset(buffer, 0, sizeof(buffer));
                size_t sz = query.receive(buffer, sizeof(buffer));
                if (sz) {
                    pending += buffer;
                }
            }
        }
    } catch(const Exception&) {
        /* chomp */
    }

    /* setup retrievers */
    cleanup();
    while (pending.length()) {
        std::string entry;
        size_t pos = pending.find('\n');
        if (pos == std::string::npos) {
            entry = pending;
            pending.clear();
        } else {
            entry = pending.substr(0, pos);
            pending = pending.substr(pos + 1);
        }

        pos = entry.find(' ');
        if (pos != std::string::npos) {
            hostaddr_t host = ntohl(inet_addr(entry.substr(0, pos).c_str()));
            hostport_t port = atoi(entry.substr(pos + 1).c_str());
            MasterQueryClient *mqc = new MasterQueryClient(*this, host, port);
            hosts.push_back(mqc);
        }
    }
}
Exemplo n.º 9
0
/**
 * Test TCP data exchange via the asynchronous sigio() mechanism
 */
void test_tcp_echo_async()
{
    TCPSocket sock;
    SocketAddress host_address;
    bool callback_triggered = false;
    int x;
    int size;

    driver.disconnect();
    TEST_ASSERT(do_connect(&driver) == 0);

    TEST_ASSERT(
        driver.gethostbyname(MBED_CONF_APP_ECHO_SERVER, &host_address) == 0);
    host_address.set_port(MBED_CONF_APP_ECHO_TCP_PORT);

    tr_debug("TCP: Server %s address: %s on port %d.",
             MBED_CONF_APP_ECHO_SERVER, host_address.get_ip_address(),
             host_address.get_port());

    TEST_ASSERT(sock.open(&driver) == 0)

    // Set up the async callback and set the timeout to zero
    sock.sigio(callback(async_cb, &callback_triggered));
    sock.set_timeout(0);

    TEST_ASSERT(sock.connect(host_address) == 0);
    // Test min, max, and some random sizes in-between
    do_tcp_echo_async(&sock, 1, &callback_triggered);
    do_tcp_echo_async(&sock, MBED_CONF_APP_TCP_MAX_PACKET_SIZE,
                      &callback_triggered);

    sock.close();

    drop_connection(&driver);

    tr_debug("TCP packets of size up to %d byte(s) echoed asynchronously and successfully.",
             MBED_CONF_APP_TCP_MAX_PACKET_SIZE);
}
Exemplo n.º 10
0
int doClientTask (const char *pszRemoteHost, unsigned short usRemotePort, bool bUseMockets, Stats *pStats)
{
    int rc;
    static char buf [1024];
    static bool bBufInitialized;

    if (!bBufInitialized) {
        srand (1234);
		for (int i = 0; i < sizeof (buf); i++) {
            buf[i] = (char) rand();
        }
        bBufInitialized = true;
    }

    if (bUseMockets) {
        StreamMocket mocket;
        if (0 != (rc = mocket.connect (pszRemoteHost, usRemotePort))) {
            fprintf (stderr, "doClientTask: failed to connect using mockets to remote host %s on port %d; rc = %d\n",
                     pszRemoteHost, usRemotePort, rc);
            return -1;
        }
        mocket.registerPeerUnreachableWarningCallback (unreachablePeerCallback, NULL);

        int iDataSize = 1024*1024;
        int iBytesSent = 0;
        int64 i64StartTime = getTimeInMilliseconds();
        mocket.send (&iDataSize, sizeof (iDataSize));
        while (iBytesSent < iDataSize) {
            mocket.send (buf, sizeof (buf));
            iBytesSent += sizeof (buf);
        }
        char chReply = 0;
        mocket.receive (&chReply, 1);
        if (chReply != '.') {
            fprintf (stderr, "doClientTask: failed to receive . from remote host\n");
            return -2;
        }
        int64 i64EndTime = getTimeInMilliseconds();
        int iTime = (int) (getTimeInMilliseconds() - i64StartTime);

        pStats->update ((double) (i64EndTime - i64StartTime));
        // Save results to a file
        FILE *file = fopen ("stats-client-streamMockets-cpp.txt", "a");
        if (file == NULL) {
            fprintf (stderr, "failed to append to file stats-mockets-cpp.txt\n");
            return -3;
        }
        fprintf (file, "[%lu]\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", (unsigned long) (getTimeInMilliseconds()/1000), iTime, 
                 mocket.getStatistics()->getSentPacketCount(),
                 mocket.getStatistics()->getSentByteCount(),
                 mocket.getStatistics()->getReceivedPacketCount(),
                 mocket.getStatistics()->getReceivedByteCount(),
                 mocket.getStatistics()->getRetransmitCount(),
                 mocket.getStatistics()->getDuplicatedDiscardedPacketCount(),
                 mocket.getStatistics()->getNoRoomDiscardedPacketCount());
                 /*mocket.getStatistics()->getDiscardedPacketCounts()._iBelowWindow,
                 mocket.getStatistics()->getDiscardedPacketCounts()._iNoRoom,
                 mocket.getStatistics()->getDiscardedPacketCounts()._iOverlap,
                 mocket.getStatistics()->getTransmitterWaitCounts()._iPacketQueueFull,
                 mocket.getStatistics()->getTransmitterWaitCounts()._iRemoteWindowFull);*/

        fclose (file);

        mocket.close();
    }
    else {
        TCPSocket socket;
        if (0 != (rc = socket.connect (pszRemoteHost, usRemotePort))) {
            fprintf (stderr, "doClientTask: failed to connect using sockets to remote host %s on port %d; rc = %d\n",
                     pszRemoteHost, usRemotePort, rc);
            return -3;
        }

        int iDataSize = 1024*1024;
        int iBytesSent = 0;
        int64 i64StartTime = getTimeInMilliseconds();
        socket.send (&iDataSize, sizeof (iDataSize));
        while (iBytesSent < iDataSize) {
            socket.send (buf, sizeof (buf));
            iBytesSent += sizeof (buf);
        }
        char chReply = 0;
        socket.receive (&chReply, 1);
        if (chReply != '.') {
            fprintf (stderr, "doClientTask: failed to receive . from remote host\n");
            return -4;
        }
        int64 i64EndTime = getTimeInMilliseconds();
        int iTime = (int) (getTimeInMilliseconds() - i64StartTime);

        pStats->update ((double) (i64EndTime - i64StartTime));

        // Save results to a file
        FILE *socfile = fopen ("statsSM-client-sockets-cpp.txt", "a");
        if (socfile == NULL) {
            fprintf (stderr, "failed to append to file statsSM-mockets-cpp.txt\n");
            return -3;
        }
    	fprintf (socfile, "[%lu]\t%d\t\n", (unsigned long) (getTimeInMilliseconds()/1000), iTime);

        fclose (socfile);

        socket.disconnect();
    }
    return 0;
}
Exemplo n.º 11
0
TCPSocket NetworkFilesystem::new_connection()
{
	TCPSocket socket;
	socket.connect(_address, _port);
	return socket;
}
int doClientTask (const char *pszRemoteHost, unsigned short usRemotePort, bool bUseMockets)
{
    int rc;
    static char buf [1024];
    static bool bBufInitialized;

    if (!bBufInitialized) {
        srand (1234);
        for (int i = 0; i < sizeof (buf); i++) {
            buf[i] = (char) rand();
        }
        bBufInitialized = true;
    }

    if (bUseMockets) {
        Mocket *pm = new Mocket();
        pm->registerPeerUnreachableWarningCallback (unreachablePeerCallback, NULL);

        puts ("doClientTask: Using Mockets:Before connect");
        if (0 != (rc = pm->connect (pszRemoteHost, usRemotePort))) {
            fprintf (stderr, "doClientTask: failed to connect using Mockets to remote host %s on port %d; rc = %d\n",
                     pszRemoteHost, usRemotePort, rc);
            puts ("doClientTask: Unable to connect");
            delete pm;
            return -11;
        }
        
        MessageSender rlsq = pm->getSender (true, true);
        MessageSender ursq = pm->getSender (false, true);

        // open stats file
        FILE *file = fopen (CLIENT_STATS_FILENAME, "a");
        if (file == NULL) {
            fprintf (stderr, "failed to append to file %s\n", CLIENT_STATS_FILENAME);
            return -12;
        }

        // mockets client code
        for (int i = 0; continue_flag; ++i) {
            // write sequence number in the first 4 bytes
            *((uint32*)buf) = EndianHelper::htonl ((uint32)i); 
            if (0 == (i % PACKET_PER_SEC)) {
                // send one reliable sequenced packet per second
                rlsq.send (buf, sizeof (buf));
            } else {
                // send an unreliable sequenced packet
                ursq.send (buf, sizeof (buf));
            }            
            sleepForMilliseconds (20);
        }

        fclose (file);
        pm->close();
        delete pm;
    } else {
        TCPSocket socket;
        puts ("doClientTask: Using Sockets:Before connect");
        if (0 != (rc = socket.connect (pszRemoteHost, usRemotePort))) {
            fprintf (stderr, "doClientTask: failed to connect using sockets to remote host %s on port %d; rc = %d\n",
                     pszRemoteHost, usRemotePort, rc);
            puts ("doClientTask: Unable to connect");
            return -11;
        }

        // open stats file
        FILE *file = fopen (CLIENT_STATS_FILENAME, "a");
        if (file == NULL) {
            fprintf (stderr, "failed to append to file %s\n", CLIENT_STATS_FILENAME);
            return -12;
        }

        // sockets client code
        for (int i = 0; continue_flag; ++i) {
            // write sequence number in the first 4 bytes
            *((uint32*)buf) = EndianHelper::htonl ((uint32)i); 
            socket.send (buf, sizeof (buf));
            sleepForMilliseconds (20);
        }

        fclose (file);
        socket.disconnect();
    }

    return 0;
}
Exemplo n.º 13
0
void ConnectThread::run()
{
	QHostInfo addr = QHostInfo::fromName(mAddress);
	if (addr.error() != QHostInfo::NoError) {
		Q_EMIT error(addr.errorString());
		return;
	}

	QHostAddress actualAddr;
	QList<QHostAddress> addresses = addr.addresses();
	for (QList<QHostAddress>::const_iterator iter = addresses.begin();
			iter != addresses.end(); ++ iter) {
		if (iter->protocol() == QAbstractSocket::IPv4Protocol) {
			actualAddr = *iter;
			break;
		}
	}

	if (actualAddr.isNull()) {
		Q_EMIT error(tr("无法解析域名: 找不到'%1'的IPv4地址").arg(mAddress));
		return;
	}

	// Begin connection
	{
		std::string addr = actualAddr.toString().toStdString();
		TCPSocketAddress remote (addr,mPort);
		IOVideoSource *src = 0;

		Error rc;
		TCPSocket *ctrl = new TCPSocket (::socket(AF_INET, SOCK_STREAM, 0));
		TCPSocket *data = new TCPSocket (::socket(AF_INET, SOCK_STREAM, 0));

		ctrl->setBlockingMode(false);
		data->setBlockingMode(false);

		ctrl->connect(&remote);
		do {
			rc = ctrl->poll(IODevice::POLL_WRITE,200);
			if (rc.isSuccess()) break;
			else if (rc.getErrorType() == Error::ERR_TIMEOUT) continue;
			else {
				rc.setErrorString("无法连接到远端服务器");
				goto connect_ctrl_failed;
			}
		}while(!mShouldStop);

		data->connect(&remote);
		do {
			rc = data->poll(IODevice::POLL_WRITE,200);
			if (rc.isSuccess()) break;
			else if (rc.getErrorType() == Error::ERR_TIMEOUT) continue;
			else {
				rc.setErrorString("无法连接到远端服务器");
				goto connect_data_failed;
			}
		}while(!mShouldStop);

		ctrl->setBlockingMode(true);
		data->setBlockingMode(true);


		src = new IOVideoSource(ctrl,data);
		rc = src->init();
		if (rc.isError()) {
			rc.setErrorString("初始化视频源失败,原因为:" + rc.getErrorString());
			goto init_video_source_failed;
		}


		mVideoSource = src;
		Q_EMIT success();
		return;

		init_video_source_failed:
		delete src;
		connect_data_failed:
		connect_ctrl_failed:
		ctrl->close();
		data->close();
		delete ctrl;
		delete data;

		Q_EMIT error(QString::fromStdString(rc.getErrorString()));

	}
}
Exemplo n.º 14
0
TCPSocket*
ModuleMap::getMapLoadingSocket( uint32 mapID,
                                uint32 loadMapRequestType,
                                const char* handshake,
                                byte zoomlevel,
                                MapSafeVector* loadedMaps,
                                uint32* mapVersion,
                                uint32* generatorVersion )
{
   uint32 mapVersionToUse = MAX_UINT32;
   uint32 generatorVersionToUse = MAX_UINT32;
   if ( mapVersion != NULL && generatorVersion != NULL ) {
      // Set the versions to use to the ones sent in
      mapVersionToUse = *mapVersion;
      generatorVersionToUse = *generatorVersion;
      // Set the ones sent in to MAX_UINT32 to detect errors
      *mapVersion = MAX_UINT32;
      *generatorVersion = MAX_UINT32;
   }
   
   DatagramReceiver receiver(8000, DatagramReceiver::FINDFREEPORT);
   
   mc2dbg4 << here << " localport " << receiver.getPort() << endl;

   uint32 mapip = MultiCastProperties::getNumericIP( MODULE_TYPE_MAP, true );
   uint16 mapport = MultiCastProperties::getPort( MODULE_TYPE_MAP, true );

   // check map set
   uint32 mapSet = Properties::getMapSet();
   if (mapSet != MAX_UINT32) {
      // code also exists in PacketContainer.cpp, move to utility function?
      mc2dbg4 << "[ModuleMap] going to change IP and port due to mapSet being set. "
                "mapSet: " << mapSet << ", IP before: " << prettyPrintIP(mapip)
             << ", port before: " << mapport << endl;
      mapip = mapip + (mapSet << 8);
      mapport = mapport | (mapSet << 13);
      mc2dbg4 << "[ModuleMap] changed IP and port. IP now: " << prettyPrintIP(mapip)
             << ", port now: " << mapport << endl;
   }
   
   uint32 status = StringTable::NOT;
   int maxRetries = 10;
   int nbrRetries = 0;

   Packet _pack(65536); // For receiving the mapreply
   DatagramSender sock;

   const int originalwaittime    =  2500000; // Wait 2.5 seconds.
   const int mapnotfoundwaittime =  2500000; // Wait 2.5 seconds.
   int waittime = originalwaittime;

   TCPSocket* TCPsock = NULL;
   
   while ( status != StringTable::OK && nbrRetries++ <= maxRetries ) {
      if ( nbrRetries > 1 ) {
         mc2log << info << here << " Retrying " << nbrRetries - 1 
                << " of " << maxRetries << endl;
      }
      if(loadedMaps != NULL)
         loadedMaps->jobThreadIsAlive(); // reset Jthread timeout clock.
      MapRequestPacket reqpack( uint16(1),  // reqID
                                uint16(1),  // PacketID
                                byte(loadMapRequestType), // Type of module
                                mapID,      // mapID
                                zoomlevel,  // Well, zoomlevel.
                                mapVersionToUse,
                                generatorVersionToUse
                                ); 
      reqpack.setOriginIP( NetUtility::getLocalIP() );
      reqpack.setOriginPort( receiver.getPort() );
      reqpack.setResendNbr((byte) nbrRetries-1);
      
      // Send request to open TCP connection between local and mapmodule
      
      if (!(sock.send(&reqpack, mapip, mapport))) {
         mc2log << error << here << " could not send - retrying"
                << endl;
         continue; // Go another round in the loop.
      }
      mc2dbg4 << "After send!" << endl;
      
      // Receive packet with ip and port to a mapModule
      if (!(receiver.receive(&_pack, waittime))) {
         mc2log << error << here << " error receiving ack - retrying"
                << endl;
         waittime = originalwaittime;
         continue; // Go another round in the loop.
      }

      bool timeout = false;
      while ( _pack.getSubType() == Packet::PACKETTYPE_ACKNOWLEDGE &&
              ! timeout ) {
         AcknowledgeRequestReplyPacket* ackPack =
            static_cast<AcknowledgeRequestReplyPacket*>(&_pack);
         uint32 packtime =
            ((AcknowledgeRequestReplyPacket*)&_pack)->getETA() * 1000;
         mc2log << info << "Got ack with " << packtime << " us delay" << endl;
         if ( ackPack->getStatus() != StringTable::OK ) {
            return NULL;
         }
         timeout = !receiver.receive(&_pack, packtime);         
      }

      if ( timeout ) {
         mc2log << error << "Got timeout after receiving ack-pack" << endl;
         continue; // Go around again
      }

      if ( _pack.getSubType() != Packet::PACKETTYPE_MAPREPLY ) {
         mc2log << error << "Got packet with subtype "
                << _pack.getSubTypeAsString()
                << " when expecting loadmapreply" << endl;
         continue; // Please try again.
      }
      
      MapReplyPacket* pack = (MapReplyPacket *)&_pack;
      
      status = pack->getStatus();
      
      if ( status != StringTable::OK || pack->getMapID() != mapID ) {
         mc2log << warn << "Got status \""
                << StringTable::getString(
                   StringTable::stringCode(pack->getStatus()),
                   StringTable::ENGLISH)
                << "\"-retrying. Wanted map = "
                << mapID
                << ", got reply for map = " << pack->getMapID() << endl;
         if ( status == StringTable::MAPNOTFOUND ) {
            // Wait longer if map not found ( loading? )
            waittime = mapnotfoundwaittime; 
         }
         if ( mapID != pack->getMapID() ) {
            status = StringTable::NOT; // Keep the loop running.
         }
         continue; // Go another round in the loop.
      }

      if ( mapVersion != NULL && generatorVersion != NULL ) {
         // Set the versions so that we know what we are caching.
         mc2dbg8 << "[ModuleMap]: Version from packet "
                 << hex << pack->getMapVersion() << ":"
                 << pack->getGeneratorVersion() << dec << endl;
         *mapVersion       = pack->getMapVersion();
         *generatorVersion = pack->getGeneratorVersion();

         // Check if new map is needed.
         if ( ! pack->newMapNeeded(mapVersionToUse,
                                   generatorVersionToUse) ) {
            // Same version. Use the cached map.
            return NULL;
         } 
      }
      
      TCPsock = new TCPSocket;      
      mc2dbg4 << here << " opening socket" << endl;
      TCPsock->open();
      
      uint32 ip = pack->getReplyIP();
      uint16 port = pack->getReplyPort();
      
      if ( ! TCPsock->connect(ip, port ) ) {
         mc2log << error << "Couldn't connect to " << ip
                << ":" << port << " - retrying" << endl;
         // Set status to not ok.
         status = StringTable::NOT;
         TCPsock->close();
         delete TCPsock;
         TCPsock = NULL;                  
         continue; // Please try again.
      }
      
      // Handshaking
      mc2dbg4 << "Starting handshake" << endl;
      int length = strlen(handshake) + 1;
      if ( TCPsock->writeAll( (byte*)handshake, length ) != length ) {
         mc2log << error << here << " handshake failed " << endl;
         status = StringTable::NOT;
         TCPsock->close();
         delete TCPsock;
         TCPsock = NULL;
         continue; // Please try again.
      } else {
         mc2dbg4 << "done" << endl;
      }
   }
   return TCPsock; // Should be NULL if we failed
}
Exemplo n.º 15
0
int main (int argc, char *argv[])
{
    #if defined (WIN32) && defined (_DEBUG)
        //getchar();    // Useful if you need to attach to the process before the break alloc happens
        _CrtSetReportMode (_CRT_ERROR, _CRTDBG_MODE_FILE);
        _CrtSetReportFile (_CRT_ERROR, _CRTDBG_FILE_STDERR);
        _CrtSetReportMode (_CRT_WARN, _CRTDBG_MODE_FILE);
        _CrtSetReportFile (_CRT_WARN, _CRTDBG_FILE_STDERR);
        //_CrtSetBreakAlloc (58);
    #endif

    if (argc < 2) {
        fprintf (stderr, "usage: %s <receiver | sender <filetosend> <server-hostname> <client-hostname> >\n", argv[0]);
        return -1;
    }
        
    pLogger = new Logger();
    pLogger->initLogFile ("filesend.log", false);
    pLogger->enableFileOutput();
    pLogger->disableScreenOutput();
    pLogger->setDebugLevel (Logger::L_MediumDetailDebug);
    
    Mocket *pMocket = new Mocket();
    pMocket->registerPeerUnreachableWarningCallback (unreachablePeerCallback, NULL);
    
    if (0 == stricmp (argv[1], "sender")) {
        if (argc != 5) {
            fprintf (stderr, "usage: %s <receiver | sender <filetosend> <server-hostname> <client-hostname> >\n", argv[0]);
            return -1;
        }
        
        pMocket->setIdentifier ("FileSend-Client");
        
        FILE *file = fopen (argv[2], "rb");
        if (file == NULL) {
            fprintf (stderr, "failed to open file %s\n", argv[2]);
            return -2;
        }

        // With this method we debug state capture by setting in mockets that only even packets can be sent.
        // Odd packets will remain in the queues and migrated to the new node along with the status of the mocket.
        pMocket->debugStateCapture();

        int rc;
        // Exchange security keys at connection time with parameter bSupportConnectivity = true
        // Or exchange keys as part of suspend/resume process with parameter bSupportConnectivity = false
        bool bSupportConnectivity = true;
        if (0 != (rc = pMocket->connect (argv[3], REM_PORT, bSupportConnectivity))) {
            fprintf (stderr, "failed to connect to host %s; rc = %d\n", argv[3], rc);
            delete pMocket;
            return -3;
        }

        char * buf = NULL;
        int n;
        int buffsize = 512;

        MessageSender sender = pMocket->getSender (true, true);
        while (true) {
            if (buffsize > 2048) {
                buffsize /= 5;
            }
            buf = (char*) malloc(buffsize);

            if ((n = fread (buf, 1, buffsize, file)) <= 0) {
                printf ("%s: EOF reached\n", argv[0]);
                free (buf);
                break;
            }
            else {
                printf("using buffer of size %d. Sending %d bytes\n", buffsize, n);
                sender.send (buf, n);
            }

            free(buf);
            // Increase the buffer size so we test with different packet dimensions
            buffsize *= 1.25;
        }
        fclose (file);
        // Suspend
        uint64 ui64StartSuspend = getTimeInMilliseconds();
        printf ("Mocket suspend finished with status %d\n", pMocket->suspend(0, 5000));
        printf ("TIME FOR SUSPENSION **  %llu  **\n", (getTimeInMilliseconds() - ui64StartSuspend));

        // Open a socket to transfer the data to the new client node
        String strNextNodeHost = argv[4];
        int iNextNodePort = 4444;
        TCPSocket *pSocketToNextNode;
        pSocketToNextNode = new TCPSocket();
        while (true) {
            printf ("trying to connect to %s:%d...\n", (const char*) strNextNodeHost, iNextNodePort);
            fflush (stdout);
            if (0 != (rc = pSocketToNextNode->connect (strNextNodeHost, iNextNodePort))) {
                printf ("failed - will try again in 2 seconds\n");
                sleepForMilliseconds (2000);
            }
            else {
                printf ("Connected\n");
                break;
            }
        }

        SocketWriter sw (pSocketToNextNode);
        BufferedWriter bw (&sw, 2048);
        
        // Freeze
        int result;
        uint64 ui64StartFreeze = getTimeInMilliseconds();
        result = pMocket->getState (&bw);
        printf ("TIME FOR GETSTATE **  %llu  **\n", (getTimeInMilliseconds() - ui64StartFreeze));
        printf ("getState ended with status %d\n", result);
        if (0 != result) {
            delete pMocket;
            return -3;
        }
    }

    else if (0 == stricmp (argv[1], "receiver")) {
        // Create the Server Socket
        int rc;
        TCPSocket *pServerSocket;
        pServerSocket = new TCPSocket();
        int iLocalPortNum = 4444;
        if (0 != (rc = pServerSocket->setupToReceive (iLocalPortNum))) {
            return -3;
        }
        printf ("listening on port %d\n", iLocalPortNum);
        
        Socket *pSocketFromPreviousNode;
        // Wait for connection from previous node
        printf ("Waiting for connection from previous node...\n");
        fflush (stdout);
        pSocketFromPreviousNode = pServerSocket->accept();
        if (pSocketFromPreviousNode == NULL) {
            printf ("Failed\n");
            return -4;
        }
        printf ("Connected\n");
        pSocketFromPreviousNode->bufferingMode(0);
        
        SocketReader sr (pSocketFromPreviousNode);
        BufferedReader br (&sr);
        
        // Resume
        int result;
        uint64 ui64StartResumeAndRestoreState = getTimeInMilliseconds();
        result = pMocket->resumeAndRestoreState (&br);
        printf ("TIME FOR RESUMEANDRESTORESTATE **  %llu  **\n", (getTimeInMilliseconds() - ui64StartResumeAndRestoreState));
        printf ("resumeFromSuspension ended with status %d\n", result);
        
        if (0 != result) {
            printf ("ERROR\n");
            delete pMocket;
            return -5;
        }

        /*
         * The connection has been restored successfully.
         * We do not set to skip odd packets with the method debugStateCapture().
         * Odd packets that were in the queues and have migrated to the new node will be sent now.
         * Sleep for a little bit before closing the connection so that the queues can be emptied.
         */
        sleepForMilliseconds (5000);

        delete (pServerSocket);
        pServerSocket = NULL;
        delete (pSocketFromPreviousNode);
        pSocketFromPreviousNode = NULL;
        pMocket->close();
    }
    else {
        printf ("ERROR\n");
        return 0;
    }
    
    printf ("Mocket statistics:\n");
    printf ("    Packets sent: %d\n", pMocket->getStatistics()->getSentPacketCount());
    printf ("    Bytes sent: %d\n", pMocket->getStatistics()->getSentByteCount());
    printf ("    Packets received: %d\n", pMocket->getStatistics()->getReceivedPacketCount());
    printf ("    Bytes received: %d\n", pMocket->getStatistics()->getReceivedByteCount());
    printf ("    Retransmits: %d\n", pMocket->getStatistics()->getRetransmitCount());

    delete pMocket;

    delete pLogger;
    pLogger = NULL;

    #if defined (WIN32) && defined (_DEBUG)
        _CrtDumpMemoryLeaks();
    #endif
    return 0;
}