Exemplo n.º 1
0
int ExtConn::connError(int errCode)
{
    LS_DBG_L(this,
             "Connection to [%s] on request #%d, confirmed %d, error: %s!",
             m_pWorker->getURL(), m_iReqProcessed, (int)m_iCPState,
             strerror(errCode));
    if (errCode == EINTR)
        return 0;
    close();
    ExtRequest *pReq = getReq();
    if (pReq)
    {
        if (((m_pWorker->getConnPool().getFreeConns() == 0)
             || ((pReq->getAttempts() % 3) == 0)) &&
            ((errCode == EPIPE) || (errCode == ECONNRESET)) &&
            (pReq->isRecoverable()) && (m_iReqProcessed) && (!m_iCPState))
        {
            pReq->incAttempts();
            pReq->resetConnector();
            if (reconnect() == 0)
                return 0;
            close();
        }
    }
    return m_pWorker->connectionError(this, errCode);
//    if ( !m_pWorker->connectionError( this, errCode ) )
//    {
//        //if (( errCode != ENOMEM )&&(errCode != EMFILE )
//        //        &&( errCode != ENFILE ))
//    }
}
Exemplo n.º 2
0
// get next frame
void CameraMJPG::update()
{
	int res = 0;

	// remove previous frame
	remove_frame();

	// get image
	while(!frame){
		if( (res = read_data(buf_read.data, buf_read.real_size))>0 )
			get_image(buf_read.data, res);
		else
			break;
	}

	if (!frame) {
		printf("[!][CameraMJPG][update] Error: cant get frame!\n");
		reconnect(); // переподключение
		return;
	}
	if(show_capture)
	{
		cvShowImage(window_name, frame);
	}
}
void WatcherStreamListDialog::newStream()
{
    TRACE_ENTER();
    emit reconnect();
    hide();
    TRACE_EXIT();
}
Exemplo n.º 4
0
static void on_transport_hup(struct irc_transport *transport)
{
	struct irc_network *network = transport->userdata;

	network_report_disconnect(network, "Hangup from server, scheduling reconnect");
	reconnect(network);
}
Exemplo n.º 5
0
void QVidiChat::timerEvent( QTimerEvent * event )
{
    if( reconnectTimerId_ == event->timerId() )
    {
        reconnect();
    }
    else if( statisticTimerId_ == event->timerId() && socket_ && socket_->isValid() && QAbstractSocket::ConnectedState == socket_->state() )
    {
        //socket_->sendTextMessage( "{\"type\":\"get_channel_counters\",\"data\":{\"channel_id\":" + channelId_ +"}}" );
        loadStatistic();
    }
    else if( saveSocketConnectionTimerId_ == event->timerId() && socket_ && socket_->state() == QAbstractSocket::ConnectedState )
    {
        //socket_->sendTextMessage( "[\"{\"type\":\"ping\",\"data\":{}}\"]" );
        socket_->sendTextMessage( "{\"type\":\"get_channel_counters\",\"data\":{\"channel_id\":" + channelId_ +"}}" );
    }
    /*
    else if( saveJoinSocketConnectionTimerId_ == event->timerId() && joinSocket_ && joinSocket_->state() == QAbstractSocket::ConnectedState )
    {
        //joinSocket_->sendTextMessage( "2" );
        joinSocket_->ping( "2" );
    }
    */

}
Exemplo n.º 6
0
static void
simple_oid_allocator(void **state)
{
	test_arg_t	*arg = *state;
	uint64_t	oid;
	int		num_oids = 29;
	int		i;
	int		rc;

	for (i = 0; i < 10; i++) {
		MPI_Barrier(MPI_COMM_WORLD);
		if (arg->myrank == 0)
			fprintf(stderr, "%d ---------------------\n", i);
		MPI_Barrier(MPI_COMM_WORLD);

		rc = daos_cont_alloc_oids(arg->coh, num_oids, &oid, NULL);
		if (rc)
			print_message("OID alloc failed (%d)\n", rc);
		assert_int_equal(rc, 0);

		print_message("%d: OID range %" PRId64 " - %" PRId64 "\n",
			      arg->myrank, oid, oid+num_oids);

		reconnect(arg);
	}
}
Exemplo n.º 7
0
/**
 * Initiates a new List Exported Devices request.
 *
 * @returns VBox status code.
 */
int USBProxyBackendUsbIp::startListExportedDevicesReq()
{
    int rc = VINF_SUCCESS;

    /*
     * Reset the current state and reconnect in case we were called in the middle
     * of another transfer (which should not happen).
     */
    Assert(m->enmRecvState == kUsbIpRecvState_None);
    if (m->enmRecvState != kUsbIpRecvState_None)
        rc = reconnect();

    if (RT_SUCCESS(rc))
    {
        /* Send of the request. */
        UsbIpReqDevList ReqDevList;
        ReqDevList.u16Version = RT_H2N_U16(USBIP_VERSION);
        ReqDevList.u16Cmd     = RT_H2N_U16(USBIP_INDICATOR_REQ | USBIP_REQ_RET_DEVLIST);
        ReqDevList.u32Status  = RT_H2N_U32(0);
        rc = RTTcpWrite(m->hSocket, &ReqDevList, sizeof(ReqDevList));
        if (RT_SUCCESS(rc))
            advanceState(kUsbIpRecvState_Hdr);
    }

    return rc;
}
Exemplo n.º 8
0
void Conn::onRead(const boost::system::error_code& error, std::shared_ptr< boost::asio::streambuf > rd_buf) {
	if( unlikely(error) ) {
		log_func("[iproto_conn] %s:%u read error: %s", ep.address().to_string().c_str(), ep.port(), error.message().c_str() );
		dismissCallbacks(CB_ERR);
		if( error != boost::asio::error::operation_aborted ) {
			reconnect();
		}
		return;
	}
	if( unlikely(!rd_buf) )
		rd_buf.reset(new boost::asio::streambuf);
	if( LOG_DEBUG )
		log_func("[iproto_conn] %s:%u onRead rd_buf->size=%zu", ep.address().to_string().c_str(), ep.port(), rd_buf->size());
	while( rd_buf->size() >= sizeof(Header) ) {
		const PacketPtr *buf = boost::asio::buffer_cast< const PacketPtr * >( rd_buf->data() );
		if( LOG_DEBUG )
			log_func("[iproto_conn] %s:%u onRead buffer iproto packet hdr: len=%u sync=%u msg=%u", ep.address().to_string().c_str(), ep.port(),
				buf->hdr.len, buf->hdr.sync, buf->hdr.msg);
		size_t want_read = sizeof(Header)+buf->hdr.len;
		if( want_read <= rd_buf->size() ) {
			invokeCallback(buf->hdr.sync, RequestResult(CB_OK, Packet(buf)) );
			rd_buf->consume( sizeof(Header) + buf->hdr.len );
		}else{
			size_t rd = want_read - rd_buf->size();
			if( LOG_DEBUG )
				log_func("[iproto_conn] %s:%u onRead want_read=%zu", ep.address().to_string().c_str(), ep.port(), rd);
			boost::asio::async_read(sock, *rd_buf, boost::asio::transfer_at_least(rd),
				boost::bind(&Conn::onRead, shared_from_this(), boost::asio::placeholders::error, rd_buf) );
			return;
		}
	}
	if( likely(sock.is_open()) )
		boost::asio::async_read(sock, *rd_buf, boost::asio::transfer_at_least(sizeof(Header)-rd_buf->size()),
			boost::bind(&Conn::onRead, shared_from_this(), boost::asio::placeholders::error, rd_buf) );
}
Exemplo n.º 9
0
void loop(void)
{
  static long lastMsg = 0;
  static int value = 0;
  char msg[50] = { '\0' };

  draw_screen();

  if (!client.connected())
  {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000)
  {
    lastMsg = now;

    ++value;
    sprintf(msg, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}
Exemplo n.º 10
0
void Conn::ensureWriteBuffer(const boost::system::error_code& error, const char *wr_buf) {
	if( unlikely(error) ) {
		log_func("[iproto_conn] %s:%u write error: %s", ep.address().to_string().c_str(), ep.port(), error.message().c_str() );
		if( error != boost::asio::error::operation_aborted ) {
			if( error == boost::asio::error::broken_pipe ) {
				//Packet was not completely transfered, we can do a retry
				write_queue.push_back( wr_buf );
				write_queue_len++;
				wr_buf=nullptr;//Prevent free
			}
			reconnect();
		}else{
			dismissCallbacks(CB_ERR);
		}
		if( likely(wr_buf != nullptr) )
			::free((void*)wr_buf);
		return;
	}
	if( likely(wr_buf != nullptr) )
		::free((void*)wr_buf);

	if( likely(write_queue_len>0 && (wr_buf || !write_is_active)) ) {
		const char *wr = write_queue.front();
		write_queue.pop_front();
		write_queue_len--;
		const Header *hdr = reinterpret_cast< const Header * >(wr);
		boost::asio::async_write(sock, boost::asio::buffer(wr, sizeof(*hdr)+hdr->len),
			boost::bind(&Conn::ensureWriteBuffer, shared_from_this(), boost::asio::placeholders::error, wr) );
		if( LOG_DEBUG )
			log_func("[iproto_conn] %s:%u write packet sync=%u len=%u", ep.address().to_string().c_str(), ep.port(), hdr->sync, hdr->len);
		write_is_active=true;
	} else
		write_is_active=false;
}
Exemplo n.º 11
0
Arquivo: net.c Projeto: saulpw/luabot
int wait_for_input(void)
{
   fd_set readfds, writefds, errfds;
   int err;

   int highestfd = 0;

   do {
     FD_ZERO(&readfds);
     FD_ZERO(&writefds);
     FD_ZERO(&errfds);

     FD_SET(g_irccnxn.sock, &readfds);
     FD_SET(g_irccnxn.sock, &writefds);
     FD_SET(g_irccnxn.sock, &errfds);
     highestfd = g_irccnxn.sock;
     
     err = select(highestfd+1, &readfds, NULL, &errfds, NULL);

     if (FD_ISSET(g_irccnxn.sock, &readfds))   /* IRC is calling.. */
         return 1;
#if 0
     if (FD_ISSET(g_irccnxn.sock, &writefds))   /* IRC is calling.. */
        return 1;
#endif
     if (FD_ISSET(g_irccnxn.sock, &errfds)) {  /* some kind of error.. */
         sleep(1);
         reconnect();
     }

     /* handle other network connections here */
   } while (err < 0);

   return 0;  /* ?? */
}
Exemplo n.º 12
0
Arquivo: rconn.c Projeto: ecks/harry
/* Drops any existing connection on 'rc', then sets up 'rc' to connect to
 * 'target' and reconnect as needed.  'target' should be a remote OpenFlow
 * target in a form acceptable to vconn_open().
 *
 * If 'name' is nonnull, then it is used in log messages in place of 'target'.
 * It should presumably give more information to a human reader than 'target',
 * but it need not be acceptable to vconn_open(). */
void
rconn_connect(struct rconn *rc, const char *target)
{
    rconn_disconnect(rc);
    rconn_set_target__(rc, target);
    reconnect(rc);
}
Exemplo n.º 13
0
rc_t MYSQLConnection::check_connect(bool_t bKeepAlive, bool_t bFix) {

  if (RC_S_OPEN != m_nStatus) { return RC_S_STATUS; }

  if (TRUE == bFix) {

    clear_all_result_set();
    ASSERT_MYSQL_API;
    int error = MYSQL_CAPI_CALL(ping)(&m_mysql);
    if (0 == error) { return RC_S_OK; }

    // fix
    return reconnect();
  }

  if (TRUE == bKeepAlive) {

    clear_all_result_set();
    ASSERT_MYSQL_API;
    int error = MYSQL_CAPI_CALL(ping)(&m_mysql);
    if (error) { RC_RETURN(RC_S_FAILED + error); }
  }

  return RC_S_OK;
}
Exemplo n.º 14
0
void StratumClient::processLoginResponce(const QJsonObject& _responceObject, const JsonRpcRequest& _request) {
  if (_responceObject.contains(JSON_RPC_TAG_NAME_ERROR) && !_responceObject.value(JSON_RPC_TAG_NAME_ERROR).isNull()) {
    qDebug() << "Login failed. JsonRPC error. Reconnecting...";
    reconnect();
    return;
  }

  if (_responceObject.value(JSON_RPC_TAG_NAME_RESULT).toObject().value(STRATUM_LOGIN_PARAM_NAME_STATUS).toString() != "OK") {
    qDebug() << "Login failed. Invalid status. Reconnecting...";
    reconnect();
    return;
  }

  m_currentSessionId = _responceObject.value(JSON_RPC_TAG_NAME_RESULT).toObject().value(STRATUM_LOGIN_PARAM_NAME_SESSION_ID).toString();
  updateJob(_responceObject.value(JSON_RPC_TAG_NAME_RESULT).toObject().value(STRATUM_LOGIN_PARAM_NAME_JOB).toObject().toVariantMap());
}
Exemplo n.º 15
0
void AbstractLink::socketDisconnected()
{
    LOG_AS("AbstractLink");

    if (d->status == Connecting)
    {
        if (d->startedTryingAt.since() < d->timeout)
        {
            // Let's try again a bit later.
            QTimer::singleShot(500, d->socket.get(), SLOT(reconnect()));
            return;
        }
        d->socket->setQuiet(false);
    }
    else
    {
        if (!d->peerAddress.isNull())
        {
            LOG_NET_NOTE("Disconnected from %s") << d->peerAddress;
        }
        else
        {
            LOG_NET_NOTE("Disconnected");
        }
    }

    d->status = Disconnected;

    emit disconnected();

    // Slots have now had an opportunity to observe the total
    // duration of the connection that has just ended.
    d->connectedAt = Time::invalidTime();
}
Exemplo n.º 16
0
void NetMonitor::reconnect(HWSession _session)
{
    saveCaptions();
    session=_session;
    title=session.getNameHostPort();
    reconnect(session.getHost(),session.getPort().toInt());
}
Exemplo n.º 17
0
fluent::Sender::Sender(
                const std::string& h, int p,
                size_t b, float _timeout, bool v)
    :  host(h), port(p), bufmax(b), timeout(_timeout), verbose(v),
        buf(nullptr), sock(Socket::INET, Socket::STREAM)
{
#ifdef FLUENT_MT
    int retval = pthread_mutex_init(&mutex, NULL);
    switch(retval)
    {
        case 0:
            /* success! */
            break;
        case EAGAIN:
            throw NoResources(EAGAIN);
            break;
        case EINVAL:
            throw InvalidAttributes();
            break;
        case ENOMEM:
            throw NoMemory();
            break;
        default:
            throw UnknownError(retval);
    }
#endif
    try {
        reconnect();
    }
    catch(...) {
        close();
    }
}
Exemplo n.º 18
0
static Msg *sms_receive(SMSCConn *conn)
{
    SmscWrapper *wrap = conn->data;
    int ret;
    Msg *newmsg = NULL;

    if (smscenter_pending_smsmessage(wrap->smsc) == 1) {

        ret = smscenter_receive_msg(wrap->smsc, &newmsg);
        if (ret == 1) {

            /* if any smsc_id available, use it */
            newmsg->sms.smsc_id = octstr_duplicate(conn->id);

	    return newmsg;
        } else if (ret == 0) { /* "NEVER" happens */
            warning(0, "SMSC %s: Pending message returned '1', "
                    "but nothing to receive!", octstr_get_cstr(conn->name));
            msg_destroy(newmsg);
            return NULL;
        } else {
            msg_destroy(newmsg);
	    if (reconnect(conn) == -1)
		smscconn_shutdown(conn, 0);
	    return NULL;
        }
    }
    return NULL;
}
Exemplo n.º 19
0
void tcp_client::run_no_wait()
{
	tcp_session::run();
	{
		boost::mutex::scoped_lock lock( m_mutex );
		if( !m_isconnected && m_isreconnect && !m_isconnecting && m_isinitconncted )
		{
			unsigned int now = (unsigned int)time( NULL );
			if( now - m_last_reconnect_time > m_reconnect_time )
				reconnect();
		}
	}

	m_cb_mgr.poll();
	int proc_index = 0;
	{
		boost::mutex::scoped_lock lock( m_msg_mutex );
		if( m_queue_recv_msg[m_current_recv_queue].empty() )
			return;
		
		proc_index = m_current_recv_queue;
		m_current_recv_queue = !m_current_recv_queue;
	}
	while( !m_queue_recv_msg[proc_index].empty() )
	{
		message_t* msg = m_queue_recv_msg[proc_index].front();
		proc_message( *msg );
		net_global::free_message( msg );
		m_queue_recv_msg[proc_index].pop();
	}
}
Exemplo n.º 20
0
std::ostream& HTTPClientSession::sendRequest(HTTPRequest& request)
{
	delete _pResponseStream;
	_pResponseStream = 0;

	bool keepAlive = getKeepAlive();
	if ((connected() && !keepAlive) || mustReconnect())
	{
		close();
		_mustReconnect = false;
	}
	try
	{
		if (!connected())
			reconnect();
		if (!keepAlive)
			request.setKeepAlive(false);
		if (!request.has(HTTPRequest::HOST))
			request.setHost(_host, _port);
		if (!_proxyHost.empty())
		{
			request.setURI(proxyRequestPrefix() + request.getURI());
			proxyAuthenticate(request);
		}
		_reconnect = keepAlive;
		_expectResponseBody = request.getMethod() != HTTPRequest::HTTP_HEAD;
		if (request.getChunkedTransferEncoding())
		{
			HTTPHeaderOutputStream hos(*this);
			request.write(hos);
			_pRequestStream = new HTTPChunkedOutputStream(*this);
		}
		else if (request.getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH)
		{
			Poco::CountingOutputStream cs;
			request.write(cs);
			_pRequestStream = new HTTPFixedLengthOutputStream(*this, request.getContentLength() + cs.chars());
			request.write(*_pRequestStream);
		}
		else if (request.getMethod() != HTTPRequest::HTTP_PUT && request.getMethod() != HTTPRequest::HTTP_POST)
		{
			Poco::CountingOutputStream cs;
			request.write(cs);
			_pRequestStream = new HTTPFixedLengthOutputStream(*this, cs.chars());
			request.write(*_pRequestStream);
		}
		else
		{
			_pRequestStream = new HTTPOutputStream(*this);
			request.write(*_pRequestStream);
		}	
		_lastRequest.update();
		return *_pRequestStream;
	}
	catch (Exception&)
	{
		close();
		throw;
	}
}
Exemplo n.º 21
0
void MqttBridge::reconnect(){
    if (!client->isConnected()){
      client->connect();
      QTimer::singleShot(2000,this,SLOT(reconnect()));
    }

}
Exemplo n.º 22
0
void tcp_client::_connect( std::string address, unsigned short port )
{
	m_endpoint.port( port );
	m_endpoint.address( boost::asio::ip::address_v4::from_string( address ) );
	reconnect();
	m_isinitconncted = true;
}
Exemplo n.º 23
0
void zmq::session_base_t::engine_error (
        zmq::stream_engine_t::error_reason_t reason)
{
    //  Engine is dead. Let's forget about it.
    engine = NULL;

    //  Remove any half-done messages from the pipes.
    if (pipe)
        clean_pipes ();

    zmq_assert (reason == stream_engine_t::connection_error
             || reason == stream_engine_t::timeout_error
             || reason == stream_engine_t::protocol_error);

    switch (reason) {
        case stream_engine_t::timeout_error:
        case stream_engine_t::connection_error:
            if (active)
                reconnect ();
            else
                terminate ();
            break;
        case stream_engine_t::protocol_error:
            terminate ();
            break;
    }

    //  Just in case there's only a delimiter in the pipe.
    if (pipe)
        pipe->check_read ();

    if (zap_pipe)
        zap_pipe->check_read ();
}
Exemplo n.º 24
0
bool Application::winEventFilter(MSG *msg, long *result)
{
    if (msg && WM_POWERBROADCAST==msg->message && PBT_APMRESUMEAUTOMATIC==msg->wParam) {
        emit reconnect();
    }
    return QCoreApplication::winEventFilter(msg, result);
}
Exemplo n.º 25
0
Network::Network(QObject* parent)
  : QObject(parent), _options(NULL), _handShakingStep(0),
    _port(3128), _retries(0)
{
  this->_ns = dynamic_cast<QNetsoul*>(parent);
  if (this->_ns)
    {
      this->_reconnectionTimer.setSingleShot(true);
      QObject::connect(&this->_reconnectionTimer, SIGNAL(timeout()),
                       this->_ns, SLOT(reconnect()));
      QObject::connect(&this->_socket, SIGNAL(readyRead()),
                       SLOT(processPackets()));
      QObject::connect(&this->_socket,
                       SIGNAL(stateChanged(QAbstractSocket::SocketState)),
                       this->_ns,
                       SLOT(updateWidgets(QAbstractSocket::SocketState)));
      QObject::connect(&this->_socket,
                       SIGNAL(stateChanged(QAbstractSocket::SocketState)),
                       this,
                       SLOT(handleSocketState(QAbstractSocket::SocketState)));
      QObject::connect(&this->_socket,
                       SIGNAL(error(QAbstractSocket::SocketError)),
                       SLOT(handleSocketError(QAbstractSocket::SocketError)));
    }
  else
    qFatal("Network constructor: parent must be a QNetsoul instance !");
  this->_socket.setProxy(QNetworkProxy::NoProxy);
}
Exemplo n.º 26
0
/* build the global (flat) graph of the universe.  this is 'flat'
in the sense that there is one data structure for the entire graph
(not 'flat' in the sense of flat edges within the same level.)
*/
static rank_t *globalize(Agraph_t *user, Agraph_t *topmodel)
{
	rank_t	*globrank;
	int		minr,maxr,r;

	/* setup bookkeeping */
	interclusterpaths(user, topmodel);

	/* allocate global ranks */
	minr = GD_minrank(topmodel);
	maxr = GD_maxrank(topmodel);
	globrank = T_array(minr,maxr,sizeof(rank_t));
	countup(user,globrank);
	for (r = minr; r <= maxr; r++) {
		globrank[r].v = N_NEW(globrank[r].n+1,Agnode_t*);	/* NIL at end */
		globrank[r].n = 0;	/* reset it */
	}

	/* installation */
	for (r = minr; r <= maxr; r++)
		installglob(user,topmodel,globrank,r);

	removejunk(user, topmodel);
	reconnect(user, topmodel);

	/* optimization */
	return globrank;
}
Exemplo n.º 27
0
static void reader(SLNPullRef const pull) {
	HTTPConnectionRef conn = NULL;
	int rc;

	for(;;) {
		if(pull->stop) goto stop;

		str_t URI[URI_MAX];

		async_mutex_lock(pull->connlock);

		rc = HTTPConnectionReadBodyLine(pull->conn, URI, sizeof(URI));
		if(rc < 0) {
			for(;;) {
				if(pull->stop) break;
				if(reconnect(pull) >= 0) break;
				if(pull->stop) break;
				async_sleep(1000 * 5);
			}
			async_mutex_unlock(pull->connlock);
			continue;
		}
		if('#' == URI[0]) { // Comment line.
			async_mutex_unlock(pull->connlock);
			continue;
		}

		async_mutex_lock(pull->mutex);
		while(pull->count + 1 > QUEUE_SIZE) {
			async_cond_wait(pull->cond, pull->mutex);
			if(pull->stop) {
				async_mutex_unlock(pull->mutex);
				async_mutex_unlock(pull->connlock);
				goto stop;
			}
		}
		size_t pos = (pull->cur + pull->count) % QUEUE_SIZE;
		pull->count += 1;
		async_mutex_unlock(pull->mutex);

		async_mutex_unlock(pull->connlock);

		for(;;) {
			if(import(pull, URI, pos, &conn) >= 0) break;
			if(pull->stop) goto stop;
			async_sleep(1000 * 5);
		}

	}

stop:
	HTTPConnectionFree(&conn);
	async_mutex_lock(pull->mutex);
	assertf(pull->stop, "Reader ended early");
	assert(pull->tasks > 0);
	pull->tasks--;
	async_cond_broadcast(pull->cond);
	async_mutex_unlock(pull->mutex);
}
    void Win32NamedPipeSessionState::implWrite(
        const std::vector<ByteBuffer> &byteBuffers,
        IocpSessionState * pReflectee)
    {
        Win32NamedPipeSessionState * pXReflectee = 
            static_cast<Win32NamedPipeSessionState *>(pReflectee);

        mPostState = Writing;

        const ByteBuffer & byteBuffer = byteBuffers.front();

        mThisPtr = mWeakThisPtr.lock();

        HANDLE & hPipe = pXReflectee ? pXReflectee->mhPipe : mhPipe ;

        bool writeOk = false;
        {
            Lock lock(mMutex);

            if (!mHasBeenClosed)
            {
                mError = 0;
                DWORD bytesWritten = 0;
                BOOL ok = WriteFile(
                    hPipe,
                    byteBuffer.getPtr(),
                    static_cast<DWORD>(byteBuffer.getLength()),
                    &bytesWritten,
                    this);

                mError = GetLastError();

                if (bytesWritten)
                {
                    writeOk = true;
                }
                else if (
                    !ok 
                    &&  (mError == ERROR_IO_PENDING || 
                        mError == WSA_IO_PENDING || 
                        mError == ERROR_MORE_DATA))
                {
                    writeOk = true;
                }
            }
        }
        if (writeOk)
        {
            mError = 0;
        }
        else
        {
            mThisPtr.reset();
            if (mEnableReconnect && mOwnFd)
            {
                reconnect();
            }
        }
    }
Exemplo n.º 29
0
/* Drops any existing connection on 'rc', then sets up 'rc' to connect to
 * 'target' and reconnect as needed.  'target' should be a remote OpenFlow
 * target in a form acceptable to vconn_open().
 *
 * If 'name' is nonnull, then it is used in log messages in place of 'target'.
 * It should presumably give more information to a human reader than 'target',
 * but it need not be acceptable to vconn_open(). */
void
rconn_connect(struct rconn *rc, const char *target, const char *name)
{
    rconn_disconnect(rc);
    rconn_set_target__(rc, target, name);
    rc->reliable = true;
    reconnect(rc);
}
Exemplo n.º 30
0
void *TCPClient::processEvent(Event *e)
{
    if (e->type() == EventSocketActive){
        if (m_bWaitReconnect && e->param())
            reconnect();
    }
    return NULL;
}