当前位置: 首页>>代码示例>>C++>>正文


C++ TCPSocket::connect方法代码示例

本文整理汇总了C++中TCPSocket::connect方法的典型用法代码示例。如果您正苦于以下问题:C++ TCPSocket::connect方法的具体用法?C++ TCPSocket::connect怎么用?C++ TCPSocket::connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在TCPSocket的用法示例。


在下文中一共展示了TCPSocket::connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: wifi_http

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");
}
开发者ID:NXPmicro,项目名称:mbed,代码行数:31,代码来源:main.cpp

示例2: Init

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;
}
开发者ID:unfabio,项目名称:furosimspark,代码行数:35,代码来源:main.cpp

示例3: _tcpsocket_connect_to_chargen_srv

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));
}
开发者ID:sg-,项目名称:mbed-os,代码行数:9,代码来源:tcpsocket_recv_100k.cpp

示例4: sendEmail

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;
}
开发者ID:,项目名称:,代码行数:51,代码来源:

示例5: _tcpsocket_connect_to_chargen_srv

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);
}
开发者ID:betzw,项目名称:mbed,代码行数:14,代码来源:tcpsocket_recv_100k.cpp

示例6: main

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;
}
开发者ID:leandrohlsilva,项目名称:SRV-Surveyor,代码行数:16,代码来源:ParallelCommunicationTest.cpp

示例7:

    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;
    }
开发者ID:HSOFEUP,项目名称:dune,代码行数:18,代码来源:Session.cpp

示例8: refresh

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);
        }
    }
}
开发者ID:goatattack,项目名称:goatattack,代码行数:42,代码来源:MasterQuery.cpp

示例9: test_tcp_echo_async

/**
 * 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);
}
开发者ID:MarceloSalazar,项目名称:mbed-os,代码行数:41,代码来源:main.cpp

示例10: doClientTask

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);

//.........这里部分代码省略.........
开发者ID:agilecomputing,项目名称:nomads,代码行数:101,代码来源:StreamIntDataTest.cpp

示例11: new_connection

TCPSocket NetworkFilesystem::new_connection()
{
	TCPSocket socket;
	socket.connect(_address, _port);
	return socket;
}
开发者ID:RobertoMalatesta,项目名称:crown,代码行数:6,代码来源:network_filesystem.cpp

示例12: doClientTask

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;
}
开发者ID:agilecomputing,项目名称:nomads,代码行数:85,代码来源:BioEnvMonitoringStation.cpp

示例13: run

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()));

	}
}
开发者ID:simophin,项目名称:remotevision,代码行数:87,代码来源:connectthread.cpp

示例14: receiver


//.........这里部分代码省略.........
      }

      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
}
开发者ID:FlavioFalcao,项目名称:Wayfinder-Server,代码行数:101,代码来源:ModuleMap.cpp

示例15: main

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;
            }
//.........这里部分代码省略.........
开发者ID:agilecomputing,项目名称:nomads,代码行数:101,代码来源:MigrationFileSend.cpp


注:本文中的TCPSocket::connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。