Esempio n. 1
0
    void Connection::onHandler(IOLoop* loop, int events)
    {
        //to prevent ref decr to 0
        ConnectionPtr_t conn = shared_from_this();
        
        if(events & TNET_READ)
        {
            handleRead();    
        }    
        
        if(events & TNET_WRITE)
        {
            if(m_status == Connecting)
            {
                handleConnect();   
            }
            else
            {
                handleWrite();    
            }
        }

        if(events & TNET_ERROR)
        {
            handleError();    
        }
    }
Esempio n. 2
0
		void TcpSession::onConnect()
		{
			if (Disconnected != _status)
				return;

			_status = Connecting;

			if (_asyncConnect)
			{
				tcp::resolver resolver(_socket.get_io_service());
				tcp::resolver::query query(_ip, _port);
				tcp::resolver::iterator iterator = resolver.resolve(query);	

				boost::asio::async_connect(_socket, iterator,
					boost::bind(&TcpSession::handleConnect, shared_from_this(), boost::asio::placeholders::error));
			}
			else
			{
				_socket.close();

				boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::from_string(_ip), boost::lexical_cast<int>(_port));
				boost::system::error_code ec;
				_socket.connect(ep, ec);

				handleConnect(ec);
			}
		}
Esempio n. 3
0
/*!
    Attempts to open a L2CAP connection between the local device with
    address \a local and the remote device with address \a remote.  The
    L2CAP PSM to use is given by \a psm.  This function should
    generally return immediately, and the socket will enter into the
    \c ConnectingState.

    The \a incomingMtu and \a outgoingMtu represent the MTU sizes to use
    for incoming and outgoing data respectively.  These parameters should
    only be considered hints and are subject to negotiation by the underlying
    stack implementation.  If the connection succeeds the actual MTUs should
    be queried by using incomingMtu() and outgoingMtu() methods.

    Optionally, the client can request that that the connection be secured
    by specifying the \a options parameter.  \bold NOTE: This feature
    might not work under some systems.

    The function returns true if the connection could be started,
    and false otherwise.

    Note that the connection could still fail, the state of the socket
    will be sent in the stateChanged() signal.

    \sa state(), connected(), waitForConnected()
 */
bool QBluetoothL2CapSocket::connect(const QBluetoothAddress &local,
                                     const QBluetoothAddress &remote,
                                     int psm,
                                     int incomingMtu,
                                     int outgoingMtu,
                                     QBluetooth::SecurityOptions options)
{
    if (state() != QBluetoothAbstractSocket::UnconnectedState)
        return false;

    resetSocketParameters();

    int sockfd = m_data->m_engine->l2capSocket();

    if (sockfd < 0) {
        setError(m_data->m_engine->error());
        return false;
    }

    m_data->m_engine->setSocketOption(sockfd, QBluetoothSocketEngine::NonBlockingOption);

    _q_setL2CapSecurityOptions(sockfd, options);

    QBluetoothAbstractSocket::SocketState connectState =
            m_data->m_engine->connectL2Cap(sockfd, local, remote, psm,
                                           incomingMtu, outgoingMtu);

    return handleConnect(sockfd, connectState);
}
Esempio n. 4
0
void Server::updateNet() {
	ENetEvent event;
	while (enet_host_service(host, &event, 0) > 0) {
		switch (event.type) {
		case ENET_EVENT_TYPE_CONNECT:
			handleConnect(event.peer);
			break;
		case ENET_EVENT_TYPE_DISCONNECT:
			handleDisconnect(event.peer, (DisconnectReason) event.data);
			break;
		case ENET_EVENT_TYPE_RECEIVE:
			handlePacket(
				event.packet->data,
				event.packet->dataLength,
				event.channelID,
				event.peer
				);
			enet_packet_destroy(event.packet);
			break;
		default:
			LOG_WARNING(logger) << "Received unknown ENetEvent type << event.type";
			break;
		}
	}
}
Esempio n. 5
0
uint32_t InnerTcpConnection::connect(uint32_t memberId, int retry) {
  InnerTcpConnectionState expectedState = INITIAL;
  if(!state.compare_exchange_strong(expectedState, CONNECTING)) {
    DVLOG(2) << "Already connecting to remote peer: " << memberId;
    return 0;
  }
  setPeerMemberId(memberId);
  /// connect to remote peer
  auto ep = ::idgs::util::singleton<idgs::actor::RpcFramework>::getInstance().getNetwork()->getEndPoint(memberId);
  if(ep == NULL) {
    LOG(ERROR) << "Network endpoint of member " << memberId << " is not available.";
    terminate();
    return RC_CLIENT_SERVER_IS_NOT_AVAILABLE;
  }
  auto& end_point = ep->tcpEndPoint;
  DVLOG(0) << "Connecting to remote peer " << memberId << '(' << end_point << ")";
  auto conn = shared_from_this();
  try {
    socket.async_connect(end_point, [conn, retry](const asio::error_code& error) {
      conn->handleConnect(error, retry);
    });
  } catch (std::exception& e) {
    LOG(ERROR) << "Failed to connect to remote peer " << memberId << ", exception: " << e.what();
    terminate();
  }

  return 0;
}
 void TcpSymbianSerial::decodedConnectionCtrl(enum ConnectionCtrl ctrl, 
                                              const char *method, uint32 src)
 {
    if (!rootPublic() || m_shutdownPrepared || m_tcpThreadPanicked) {
       WARN("Won't handle connectioncontrol.");
       return;
    }
    switch(ctrl){
    case CONNECT:
       DBG("CONNECT %s", method);
       handleConnect(method, src);
       break;
    case DISCONNECT:
       DBG("DISCONNECT %s", method);
       handleDisconnect(method, src);
       break;
    case QUERY:
       DBG("QUERY %s", method);
       {
          enum ConnectionNotifyReason reason = UNSPECIFIED;
          //no lastsent check here. This is after all an explicit request.
          rootPublic()->connectionNotify(m_state, reason, src);
       }
       break;
    default:
       ERR("ConnectionCtrl: Unknown ctrl value: %d", ctrl);
    }
    DBG("end of decodedConnectionCtrl");
 }
Esempio n. 7
0
/*!
    Attempts to open a RFCOMM connection between the local device with
    address \a local and the remote device with address \a remote.  The
    RFCOMM channel to use is given by \a channel.  This function should
    generally return immediately, and the socket will enter into the
    \c ConnectingState.

    Optionally the client can request that the connection be secured
    by specifying the \a options parameter.  \bold NOTE: This feature
    might not work under some systems.  The options will be set
    but might be ignored by the implementation.

    The function returns true if the connection process could be started,
    and false otherwise.

    Note that the connection could still fail, the state of the socket
    will be sent in the stateChanged() signal.

    \sa state(), connected(), waitForConnected()
 */
bool QBluetoothRfcommSocket::connect(const QBluetoothAddress &local,
                                       const QBluetoothAddress &remote,
                                       int channel,
                                       QBluetooth::SecurityOptions options)
{
    if (state() != QBluetoothAbstractSocket::UnconnectedState)
        return false;

    resetSocketParameters();

    int sockfd = m_data->m_engine->rfcommSocket();

    if (sockfd < 0) {
        setError(m_data->m_engine->error());
        return false;
    }

    m_data->m_engine->setSocketOption(sockfd, QBluetoothSocketEngine::NonBlockingOption);

    if (!_q_setSecurityOptions(sockfd, options))
        qWarning("Cannot set security options for RFCOMM socket %d", sockfd);

    QBluetoothAbstractSocket::SocketState connectState =
            m_data->m_engine->connectRfcomm(sockfd, local, remote, channel);

    return handleConnect(sockfd, connectState);
}
Esempio n. 8
0
std::string CPanasonicNode::handleWriteAndRead(std::string pMessageToSend)
{

	if (DEBUG_LOGGING) _log.Log(LOG_NORM, "Panasonic Plugin: (%s) Handling message: '%s'.", m_Name.c_str(), pMessageToSend.c_str());
	boost::asio::io_service io_service;
	// Get a list of endpoints corresponding to the server name.
	boost::asio::ip::tcp::resolver resolver(io_service);
	boost::asio::ip::tcp::resolver::query query(m_IP, (m_Port[0] != '-' ? m_Port : m_Port.substr(1)));
	boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query);
	boost::asio::ip::tcp::endpoint endpoint = *iter;
	boost::asio::ip::tcp::resolver::iterator end;

	// Try each endpoint until we successfully establish a connection.
	boost::asio::ip::tcp::socket socket(io_service);
	boost::system::error_code error = boost::asio::error::host_not_found;
	while (error && iter != end)
	{
		socket.close();
		if (handleConnect(socket, *iter, error)) 
		{
			if (DEBUG_LOGGING) _log.Log(LOG_NORM, "Panasonic Plugin: (%s) Connected.'.", m_Name.c_str());
			break;
		}
		else
			iter++;
	}
	if (error)
	{
		if (DEBUG_LOGGING) _log.Log(LOG_ERROR, "Panasonic Plugin: (%s) Error trying to connect.'.", m_Name.c_str());
		socket.close();
		return "ERROR";
	}

	boost::array<char, 512> _Buffer;
	size_t request_length = std::strlen(pMessageToSend.c_str());
	if (DEBUG_LOGGING) _log.Log(LOG_NORM, "Panasonic Plugin: (%s) Attemping write.'.", m_Name.c_str());
	
	try
	{
		boost::asio::write(socket, boost::asio::buffer(pMessageToSend.c_str(), request_length));
		if (DEBUG_LOGGING) _log.Log(LOG_NORM, "Panasonic Plugin: (%s) Attemping read.'.", m_Name.c_str());
		size_t reply_length = boost::asio::read(socket, boost::asio::buffer(_Buffer, request_length));
		//_log.Log(LOG_NORM, "Panasonic Plugin: (%s) Error code: (%i).'.", m_Name.c_str(),error);
		socket.close();
		std::string pReceived(_Buffer.begin(), reply_length);
		return pReceived;
	}
	catch (...)
	{
		//_log.Log(LOG_ERROR, "Panasonic Plugin: (%s) Exception in Write/Read message: %s", m_Name.c_str(), e.what());
		socket.close();
		std::string error = "ERROR";
		return error;
	}
}
Esempio n. 9
0
    SimpleHttpResult* SimpleHttpClient::request (int method,
            const string& location,
            const char* body,
            size_t bodyLength,
            const map<string, string>& headerFields) {
      
      _result = new SimpleHttpResult;
      _errorMessage = "";

      // set body to all connections
      setRequest(method, location, body, bodyLength, headerFields);

      double endTime = now() + _requestTimeout;
      double remainingTime = _requestTimeout;

      while (isWorking() && remainingTime > 0.0) {
        switch (_state) {
          case (IN_CONNECT):
            handleConnect();
            break;

          case (IN_WRITE):
            handleWrite(remainingTime);
            break;

          case (IN_READ_HEADER):
          case (IN_READ_BODY):
          case (IN_READ_CHUNKED_HEADER):
          case (IN_READ_CHUNKED_BODY):
            handleRead(remainingTime);
            break;
          default:
            break;
        }

        remainingTime = endTime - now();
      }
      
      if (isWorking() && _errorMessage=="" ) {
        if (_warn) {
          LOGGER_WARNING << "Request timeout reached.";
        }
        _errorMessage = "Request timeout reached.";
      }
      
      // set result type in getResult()
      SimpleHttpResult* result = getResult();
      
      _result = 0;
      
      return result;
    }
Esempio n. 10
0
UtlBoolean XCpCall::handleCommandMessage(const AcCommandMsg& rRawMsg)
{
   switch ((AcCommandMsg::SubTypeEnum)rRawMsg.getMsgSubType())
   {
   case AcCommandMsg::AC_CONNECT:
      handleConnect((const AcConnectMsg&)rRawMsg);
      return TRUE;
   case AcCommandMsg::AC_START_RTP_REDIRECT:
      handleStartRtpRedirect((const AcStartRtpRedirectMsg&)rRawMsg);
      return TRUE;
   case AcCommandMsg::AC_STOP_RTP_REDIRECT:
      handleStopRtpRedirect((const AcStopRtpRedirectMsg&)rRawMsg);
      return TRUE;
   case AcCommandMsg::AC_DROP_CONNECTION:
      handleDropConnection((const AcDropConnectionMsg&)rRawMsg);
      return TRUE;
   default:
      break;
   }

   // we couldn't handle it, give chance to parent
   return XCpAbstractCall::handleCommandMessage(rRawMsg);
}
Esempio n. 11
0
    SimpleHttpResult* SimpleHttpClient::request (rest::HttpRequest::HttpRequestType method,
            const string& location,
            const char* body,
            size_t bodyLength,
            const map<string, string>& headerFields) {
     
      assert(_result == 0);
       
      _result = new SimpleHttpResult;
      _errorMessage = "";

      // set body to all connections
      setRequest(method, location, body, bodyLength, headerFields);

      double endTime = now() + _requestTimeout;
      double remainingTime = _requestTimeout;

      while (isWorking() && remainingTime > 0.0) {
        switch (_state) {
          case (IN_CONNECT): {
            handleConnect();
            break;
          }

          case (IN_WRITE): {
            size_t bytesWritten = 0;

            TRI_set_errno(TRI_ERROR_NO_ERROR);
            if (! _connection->handleWrite(remainingTime, (void*) (_writeBuffer.c_str() + _written), _writeBuffer.length() - _written, &bytesWritten)) {
              setErrorMessage(TRI_last_error(), false);
              this->close();
            }
            else {
              _written += bytesWritten;
              if (_written == _writeBuffer.length())  {
                _state = IN_READ_HEADER;        
              }
            }
            break;
          }

          case (IN_READ_HEADER):
          case (IN_READ_BODY):
          case (IN_READ_CHUNKED_HEADER):
          case (IN_READ_CHUNKED_BODY): {
            TRI_set_errno(TRI_ERROR_NO_ERROR);
            if (_connection->handleRead(remainingTime, _readBuffer)) {
              switch (_state) {
                case (IN_READ_HEADER):
                  readHeader();
                  break;
                case (IN_READ_BODY):
                  readBody();
                  break;
                case (IN_READ_CHUNKED_HEADER):
                  readChunkedHeader();
                  break;
                case (IN_READ_CHUNKED_BODY):
                  readChunkedBody();
                  break;
                default:
                  break;
              }
            }
            else {
              setErrorMessage(TRI_last_error(), false);
              this->close();
            }
            break;
          }
          default:
            break;
        }

        remainingTime = endTime - now();
      }
      
      if (isWorking() && _errorMessage == "" ) {
        setErrorMessage("Request timeout reached");
      }
      
      // set result type in getResult()
      SimpleHttpResult* result = getResult();
      
      _result = 0;
      
      return result;
    }
Esempio n. 12
0
PlayerWidget::PlayerWidget( int index, Database *database,
                            ControlWidget *controlWidget, Qt::WindowFlags flags )
: QWidget( controlWidget, flags )
, mPlayer( index )
, mpDatabase( database )
, mpControlWidget( controlWidget )
, mpScrollLine( new ScrollLine( this ) )
, mpStatusDisplay( new QLabel( this ) )
, mpTimeDisplay( new QLabel( this ) )
, mpPlayPosition( new TimeSlider( Qt::Horizontal, this ) )
, mpSocket( new QTcpSocket( this ) )
, mpFSM( new PlayerFSM( this ) )
, mStartOther( false )
, mAutoPlay( false )
, mTotalTime( 0 )
, mFrequency( 44100 )
, mSamples( 0 )
, mHeadStart( 10 )
, mUpdateSlider( true )
, mKioskMode( false )
, mDisplayPattern()
, mTrackInfo()
{
   QVBoxLayout *mainLayout = new QVBoxLayout( this );

   mainLayout->setContentsMargins( 0, 0, 0, 0 );
   mainLayout->setSpacing( 5 );
   mainLayout->addWidget( mpScrollLine );
   mainLayout->addWidget( mpTimeDisplay );
   mainLayout->addWidget( mpStatusDisplay );
   mainLayout->addWidget( mpPlayPosition );
   setLayout( mainLayout );

   mpStatusDisplay->setAlignment( Qt::AlignLeft );
   mpStatusDisplay->setFrameShape( QFrame::Box );
   mpStatusDisplay->setContextMenuPolicy( Qt::CustomContextMenu );
   mpStatusDisplay->setObjectName( QString("StatusLabel") );
   mpTimeDisplay->setAlignment( Qt::AlignRight );
   mpTimeDisplay->setFrameShape( QFrame::Box );
   mpTimeDisplay->setObjectName( QString("TimeLabel") );
   mpPlayPosition->setTickPosition( QSlider::TicksBelow );
   mpPlayPosition->setTickInterval( 60 );
   mpPlayPosition->setMaximum( 1 );

   connect( mpSocket, SIGNAL(connected()),
            this, SLOT(handleConnect()) );
   connect( mpSocket, SIGNAL(disconnected()),
            this, SLOT(handleDisconnect()) );
   connect( mpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(handleError(QAbstractSocket::SocketError)) );
   connect( mpSocket, SIGNAL(readyRead()),
            this, SLOT(handleResponse()) );

   connect( mpPlayPosition, SIGNAL(sliderPressed()),
            this, SLOT(lock()) );
   connect( mpPlayPosition, SIGNAL(sliderReleased()),
            this, SLOT(seek()) );
   connect( mpPlayPosition, SIGNAL(actionTriggered(int)),
            this, SLOT(playPosChange(int)) );
   connect( mpStatusDisplay, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(unload()) );

   mpFSM->changeState( PlayerFSM::disconnected );
}
Esempio n. 13
0
    SimpleHttpResult* SimpleHttpClient::request (
      rest::HttpRequest::HttpRequestType method,
      std::string const& location,
      char const* body,
      size_t bodyLength,
      std::map<std::string, std::string> const& headerFields) {
      
      // ensure connection has not yet been invalidated
      TRI_ASSERT(_connection != nullptr);

      // ensure that result is empty
      TRI_ASSERT(_result == nullptr);

      // create a new result
      _result = new SimpleHttpResult;

      // reset error message
      _errorMessage = "";

      // set body
      setRequest(method, rewriteLocation(location), body, bodyLength, headerFields);

      // ensure state
      TRI_ASSERT(_state == IN_CONNECT || _state == IN_WRITE);

      // respect timeout
      double endTime = TRI_microtime() + _requestTimeout;
      double remainingTime = _requestTimeout;

      while (_state < FINISHED && remainingTime > 0.0) {
        // Note that this loop can either be left by timeout or because
        // a connect did not work (which sets the _state to DEAD). In all
        // other error conditions we call close() which resets the state
        // to IN_CONNECT and tries a reconnect. This is important because
        // it is always possible that we are called with a connection that
        // has already been closed by the other side. This leads to the
        // strange effect that the write (if it is small enough) proceeds
        // but the following read runs into an error. In that case we try
        // to reconnect one and then give up if this does not work.
        switch (_state) {
          case (IN_CONNECT): {
            handleConnect();
            // If this goes wrong, _state is set to DEAD
            break;
          }

          case (IN_WRITE): {
            size_t bytesWritten = 0;

            TRI_set_errno(TRI_ERROR_NO_ERROR);

            bool res = _connection->handleWrite(
              remainingTime, 
              static_cast<void const*>(_writeBuffer.c_str() + _written),
              _writeBuffer.length() - _written,
              &bytesWritten);

            if (! res) {
              setErrorMessage("Error writing to '" +
                              _connection->getEndpoint()->getSpecification() +
                              "' '" +
                              _connection->getErrorDetails() +
                              "'");
              this->close(); // this sets _state to IN_CONNECT for a retry
            }
            else {
              _written += bytesWritten;

              if (_written == _writeBuffer.length())  {
                _state = IN_READ_HEADER;
              }
            }

            break;
          }

          case (IN_READ_HEADER):
          case (IN_READ_BODY):
          case (IN_READ_CHUNKED_HEADER):
          case (IN_READ_CHUNKED_BODY): {
            TRI_set_errno(TRI_ERROR_NO_ERROR);

            // we need to notice if the other side has closed the connection:
            bool connectionClosed;

            bool res = _connection->handleRead(remainingTime,
                                               _readBuffer,
                                               connectionClosed);


            // If there was an error, then we are doomed:
            if (! res) {
              setErrorMessage("Error reading from: '" +
                              _connection->getEndpoint()->getSpecification() +
                              "' '" +
                              _connection->getErrorDetails() +
                              "'");
              this->close(); // this sets the state to IN_CONNECT for a retry
              break;
            }

            if (connectionClosed) {
              // write might have succeeded even if the server has closed 
              // the connection, this will then show up here with us being
              // in state IN_READ_HEADER but nothing read.
              if (_state == IN_READ_HEADER && 0 == _readBuffer.length()) {
                this->close(); // sets _state to IN_CONNECT again for a retry
                continue;
              }

              else if (_state == IN_READ_BODY && ! _result->hasContentLength()) {
                // If we are reading the body and no content length was
                // found in the header, then we must read until no more
                // progress is made (but without an error), this then means
                // that the server has closed the connection and we must
                // process the body one more time:
                _result->setContentLength(_readBuffer.length() - _readBufferOffset);
                processBody();

                if (_state != FINISHED) {
                  // If the body was not fully found we give up:
                  this->close(); // this sets the state IN_CONNECT to retry
                }

                break;
              }

              else {
                // In all other cases of closed connection, we are doomed:
                this->close(); // this sets the state to IN_CONNECT retry
                break;
              }
            }

            // the connection is still alive:
            switch (_state) {
              case (IN_READ_HEADER):
                processHeader();
                break;

              case (IN_READ_BODY):
                processBody();
                break;

              case (IN_READ_CHUNKED_HEADER):
                processChunkedHeader();
                break;

              case (IN_READ_CHUNKED_BODY):
                processChunkedBody();
                break;

              default:
                break;
            }

            break;
          }

          default:
            break;
        }

        remainingTime = endTime - TRI_microtime();
      }

      if (_state < FINISHED && _errorMessage.empty()) {
        setErrorMessage("Request timeout reached");
      }

      // set result type in getResult()
      SimpleHttpResult* result = getResult();

      _result = nullptr;

      return result;
    }