예제 #1
0
파일: QRBG.cpp 프로젝트: QuHub/lx-quSyn
// Connects to service server and on success, stores connected socket handle
// in private class member.
// Upon failure, exception is thrown.
void QRBG::Connect() throw(ConnectError) {
	if (hSocket != -1) {
		// we're already connected
		return;
	}

	if (!*szHostname || !port) {
		// server address is not defined
		throw ConnectError();
	}

	int hsock = static_cast<int>( socket(AF_INET, SOCK_STREAM, 0) );
	if (hsock == -1) {
		// failed to create socket
		throw ConnectError();
	}

	// try to resolve 'hostname', if we fail, assume 'hostname' as an IP address
	struct sockaddr_in addr;
	struct hostent *hent = gethostbyname(szHostname);
	if (hent == NULL)
		addr.sin_addr.s_addr = inet_addr(szHostname);
	else
		memcpy(&addr.sin_addr, hent->h_addr, hent->h_length);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);

	if (connect(hsock, (struct sockaddr *)&addr, sizeof(addr))) {
		// failed to connect
		throw ConnectError();
	}

	hSocket = hsock;
}
예제 #2
0
  void TcpConnect::HandleDataWrite(const boost::system::error_code& err, int write_size){

    if (state_ == CS_CLOSED){
      return;
    }

    if (err){
      //LOG(ERROR) << err.message();
      return ConnectError(err);
    }
    is_writing_ = false;

    if (!write_buffer_->Consume(write_size)){
      //LOG(ERROR) << "Nver reach here";
      return ConnectError(boost::asio::error::invalid_argument);
    }
    if (write_buffer_->Length() > 0){
      // Continue write data
      WriteData();
    }
    else if (write_buffer_->Length() == 0){
      // //LOG(INFO) << write_size;
      SignalConnectWrite(shared_from_this());
    }
    else{
      BOOST_ASSERT(0);
    }
  }
예제 #3
0
/*! opens a connection to a remote server at given \p hostname and \p port number.
 *
 * \param hostname the hostname of the host to connect to.
 * \param port the TCP port number to connect to.
 *
 * \throw ConnectError if connection to given host failed.
 *
 * \todo asynchronous/nonblocking connect()
 * \todo DNS resolving
 */
void NetMessageSocket::open(const std::string& hostname, int port)
{
	int fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd < 0)
		throw ConnectError("socket", errno);

	sockaddr_in sin;
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(port);

	// TODO support DNS resolving.
	int rc;
	if ((rc = inet_pton(AF_INET, hostname.c_str(), &sin.sin_addr.s_addr)) <= 0) {
		::close(fd);
		if (rc == 0)
			throw ConnectError("Address not in representation format.");
		else
			throw ConnectError("inet_pton", errno);
	}

	rc = connect(fd, (sockaddr*)&sin, sizeof(sin));
	if (rc < 0) {
		perror("connect");
		::close(fd);
		throw ConnectError("connect", errno);
	}

	fd_ = fd;
}
예제 #4
0
	//-------------------------------------------------------------------------
	int Handler::Handle( Asev::Event &e ) {
		if( e.Info() != typeid( Event ) ) return 0;

#define GETERROR static_cast<ErrorEvent&>(e).GetError()
		  
		int result = 0;
		Event &stream_event = static_cast<Event&>(e);
		switch( stream_event.m_class ) {
		case Event::ACCEPTED:
			Accepted( stream_event.m_stream );
			break;
		case Event::ACCEPTERROR:
			AcceptError( stream_event.m_stream, GETERROR );
			break;
		case Event::CONNECTED:
			Connected( stream_event.m_stream );
			break;
		case Event::CONNECTERROR:
			ConnectError( stream_event.m_stream, GETERROR );
			break;
		case Event::DISCONNECTED:
			Disconnected( stream_event.m_stream, GETERROR );
			break;
		case Event::RECEIVE:
			Receive( stream_event.m_stream, 
					static_cast<Event::Receive&>(e).GetMessage() );
			break;
		case Event::SENDFAILED:
			SendFailed( stream_event.m_stream, GETERROR );
			break;
		}
		return result;
	}
예제 #5
0
void Client::connect(std::string hostname, int tcpPort)
{
    if (tcpServer->connect(hostname, tcpPort)) 
    {
        int tcpSocket = tcpServer->getSocket();
        fdManager.add(tcpSocket, this);
    }
    else
    {
        throw ConnectError();
    }
}
예제 #6
0
  void TcpConnect::HandleReadData(const boost::system::error_code& err, int read_size){

    if (state_ == CS_CLOSED){
      return;
    }

    if (err){
      //LOG(ERROR) << err.message();
      return ConnectError(err);
    }

    read_buffer_->WriteBytes(pre_read_buffer_, read_size);

    // -------------------------------------------------------------------------
    while (read_buffer_->Length() >= HEADER_BUFFERR_SIZE){
      memcpy(read_header_buffer_, read_buffer_->Data(), HEADER_BUFFERR_SIZE);
      if (read_header_buffer_[0] != VZ_HEADER[0] || read_header_buffer_[1] != VZ_HEADER[1]){
        //LOG(ERROR) << "The packet header VZ getting error";
        return ConnectError(boost::asio::error::invalid_argument);
      }
      uint16 flag = *((uint16*)(read_header_buffer_ + 2));
      uint32 packet_size = *(uint32*)(read_header_buffer_ + 4);
      flag = ntohs(flag);
      packet_size = ntohl(packet_size);
      if (packet_size > MAX_PKT_SIZE){
        //LOG(ERROR) << "The packet size large than " << MAX_PKT_SIZE;
        return ConnectError(boost::asio::error::invalid_argument);
      }
      if (packet_size <= (read_buffer_->Length() - HEADER_BUFFERR_SIZE)){
        SignalConnectRead(shared_from_this(),
          read_buffer_->Data() + HEADER_BUFFERR_SIZE, packet_size, flag);
        read_buffer_->Consume(packet_size + HEADER_BUFFERR_SIZE);
      }
      else{
        break;
      }
    }
    AsyncReadData();
  }
예제 #7
0
// 连接数据库
void ConnectorMySQL::connect()
{
    if (!is_connected())
    {
        int reconnect = 1;
        mysql_init(&mysql_);
        mysql_options(&mysql_, MYSQL_OPT_RECONNECT, &reconnect);
        connected_ = mysql_real_connect(&mysql_, host_.c_str(), user_.c_str(), passwd_.c_str(), NULL, port_, NULL, 0) != NULL;
        if (mysql_errno(&mysql_) != 0)
        {
            throw ConnectError(mysql_error(&mysql_));
        }
        mysql_set_server_option(&mysql_, MYSQL_OPTION_MULTI_STATEMENTS_OFF);
    }
}
예제 #8
0
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QMainWindow::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: on_clearButton_clicked(); break;
        case 1: on_getLastTempButton_clicked(); break;
        case 2: on_getTempButton_clicked(); break;
        case 3: on_getTempAllButton_clicked(); break;
        case 4: DataReceived((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 5: ConnectError(); break;
        case 6: timerEvent((*reinterpret_cast< QTimerEvent*(*)>(_a[1]))); break;
        default: ;
        }
        _id -= 8;
    }
    return _id;
}
예제 #9
0
void ReceiveThread::run()
{
	std::cout<<"in ReceiveThread:: run ++++++++++++++"<<std::endl;
	if(receiveSocket==NULL)
	{
	receiveSocket = new QTcpSocket;
	creatconnect();
	}

	if(tryNewConnect())
		emit connected();
	else 
	{
		std::cout<<"in ReceiveThread::run, send ConnectError "<<std::endl;
		emit ConnectError();
		return ;
	}	
	exec();
	
	//receiveSocket->waitForDisconnected();
	//emit receiveData();
}
예제 #10
0
void ReceiveThread::StartRun(ConnectInfo &robotinfo)
{
	std::cout<<"ReceiveThread::StartRun-------- "<<std::endl;
	receiveRobot->Copy(robotinfo);
    
	if(receiveSocket==NULL)
	{
    std::cout<<"in ReceiveThread::StartRun,new QTcpSocket "<<std::endl;
	receiveSocket = new QTcpSocket;
	 creatconnect();
	}
	
	if(tryNewConnect())
	emit connected();
	else 
	{
		std::cout<<"in ReceiveThread::StartRun,  ConnectError "<<std::endl;
		emit ConnectError();
		return ;
	}	
	//exec();
}
예제 #11
0
//===================
//     PRIVATE
//===================
bool WebServer::setupWebSocket(quint16 port){
  WSServer = new QWebSocketServer("sysadm-server", QWebSocketServer::SecureMode, this);
  //SSL Configuration
  QSslConfiguration config = QSslConfiguration::defaultConfiguration();
	QFile CF( QStringLiteral(SSLCERTFILE) ); 
	  if(CF.open(QIODevice::ReadOnly) ){
	    QSslCertificate CERT(&CF,QSsl::Pem);
	    config.setLocalCertificate( CERT );
	    CF.close();   
	  }else{
	    qWarning() << "Could not read WS certificate file:" << CF.fileName();
	  }
	QFile KF( QStringLiteral(SSLKEYFILE));
	  if(KF.open(QIODevice::ReadOnly) ){
	    QSslKey KEY(&KF, QSsl::Rsa, QSsl::Pem);
	    config.setPrivateKey( KEY );
	    KF.close();	
	  }else{
	    qWarning() << "Could not read WS key file:" << KF.fileName();
	  }
	config.setPeerVerifyMode(QSslSocket::VerifyNone);
	config.setProtocol(SSLVERSION);
  WSServer->setSslConfiguration(config);
  //Setup Connections
  connect(WSServer, SIGNAL(newConnection()), this, SLOT(NewSocketConnection()) );
  connect(WSServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), this, SLOT(NewConnectError(QAbstractSocket::SocketError)) );
  //  -- websocket specific signals
  connect(WSServer, SIGNAL(closed()), this, SLOT(ServerClosed()) );
  connect(WSServer, SIGNAL(serverError(QWebSocketProtocol::CloseCode)), this, SLOT(ServerError(QWebSocketProtocol::CloseCode)) );
  connect(WSServer, SIGNAL(originAuthenticationRequired(QWebSocketCorsAuthenticator*)), this, SLOT(OriginAuthRequired(QWebSocketCorsAuthenticator*)) );
  connect(WSServer, SIGNAL(peerVerifyError(const QSslError&)), this, SLOT(PeerVerifyError(const QSslError&)) );
  connect(WSServer, SIGNAL(sslErrors(const QList<QSslError>&)), this, SLOT(SslErrors(const QList<QSslError>&)) );
  connect(WSServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), this, SLOT(ConnectError(QAbstractSocket::SocketError)) );
  //Now start the server
  return WSServer->listen(QHostAddress::Any, port);
}