Exemple #1
0
/*线程启动时调用的函数*/
void ServerThread::run()
{
    _clientSocket = new ClientSocket();
    /*用ServerThread保存的套接字描述符初始化套接字*/
    if(!_clientSocket->setSocketDescriptor(_descriptor))
    {
        qDebug("socket create fail!");
        this->finished();
        return;
    }
    /*连接消息发送信号*/
    connect(this,SIGNAL(sendData(int,qint32,QVariant)),
            _clientSocket,SLOT(sendData(int,qint32,QVariant)));
    /*连接消息到达信号*/
    connect(_clientSocket,SIGNAL(messageArrive(int,qint32,QVariant)),
            this,SIGNAL(messageArrive(int,qint32,QVariant)));
    /*连接客户端断开信号*/
    connect(_clientSocket,SIGNAL(disconnected()),this,SLOT(threadFinished()));
    /*连接数据到达信号*/
    connect(_clientSocket,SIGNAL(readyRead()),_clientSocket,SLOT(readData()));
    exec();
}
squeezeListner::squeezeListner(QObject *parent,QString mIpaddr,QString mPortNr)
 :QObject ( parent )
{
    bool ret;
    ret=false;

    port_nr=mPortNr;
    ip_addr=mIpaddr;
    tcpSocket = new QTcpSocket(this);
    if (QObject::connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readData1())));
        qDebug()<<"Signal ok";
    QObject::connect(tcpSocket, SIGNAL(disconnected()),this,SLOT(disConnected()));

    tcpSocket->abort();
    tcpSocket->connectToHost(ip_addr,port_nr.toInt());

    if (tcpSocket->waitForConnected(1000))
    {
        ret=true;
        qDebug("Connected!");
    }
}
KDSoapServerSocket *KDSoapSocketList::handleIncomingConnection(int socketDescriptor)
{
    KDSoapServerSocket *socket = new KDSoapServerSocket(this, m_serverObject);
    socket->setSocketDescriptor(socketDescriptor);

#ifndef QT_NO_OPENSSL
    if (m_server->features() & KDSoapServer::Ssl) {
        // We could call a virtual "m_server->setSslConfiguration(socket)" here,
        // if more control is needed (e.g. due to SNI)
        if (!m_server->sslConfiguration().isNull()) {
            socket->setSslConfiguration(m_server->sslConfiguration());
        }
        socket->startServerEncryption();
    }
#endif

    QObject::connect(socket, SIGNAL(disconnected()),
                     socket, SLOT(deleteLater()));
    m_sockets.insert(socket);
    connect(socket, SIGNAL(socketDeleted(KDSoapServerSocket*)), this, SLOT(socketDeleted(KDSoapServerSocket*)));
    return socket;
}
Exemple #4
0
CloudConnection::CloudConnection(const QUrl &authenticationServer, const QUrl &proxyServer, QObject *parent) :
    QObject(parent),
    m_authenticationServerUrl(authenticationServer),
    m_proxyServerUrl(proxyServer),
    m_connected(false),
    m_error(Cloud::CloudErrorNoError)
{
    m_reconnectionTimer = new QTimer(this);
    m_reconnectionTimer->setSingleShot(false);
    connect(m_reconnectionTimer, &QTimer::timeout, this, &CloudConnection::reconnectionTimeout);

    m_connection = new QWebSocket("guhd", QWebSocketProtocol::Version13, this);
    connect(m_connection, SIGNAL(connected()), this, SLOT(onConnected()));
    connect(m_connection, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
    connect(m_connection, SIGNAL(textMessageReceived(QString)), this, SLOT(onTextMessageReceived(QString)));
    connect(m_connection, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onError(QAbstractSocket::SocketError)));

    m_authenticator = new CloudAuthenticator("0631d42ba0464e4ebd4b78b15c53f532", "b7919ebf3bcf48239f348e764744079b", this);
    m_authenticator->setUrl(m_authenticationServerUrl);

    connect(m_authenticator, &CloudAuthenticator::authenticationChanged, this, &CloudConnection::onAuthenticationChanged);
}
Exemple #5
0
void QDeclarativeBluetoothSocket::newSocket(QBluetoothSocket *socket, QDeclarativeBluetoothService *service)
{
    if (d->m_socket){
        delete d->m_socket;
    }

    d->m_service = service;
    d->m_socket = socket;
    d->m_connected = true;
    d->m_componentCompleted = true;
    d->m_error = NoError;

    QObject::connect(socket, SIGNAL(connected()), this, SLOT(socket_connected()));
    QObject::connect(socket, SIGNAL(disconnected()), this, SLOT(socket_disconnected()));
    QObject::connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SLOT(socket_error(QBluetoothSocket::SocketError)));
    QObject::connect(socket, SIGNAL(stateChanged(QBluetoothSocket::SocketState)), this, SLOT(socket_state(QBluetoothSocket::SocketState)));
    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(socket_readyRead()));

    socket_state(socket->state());

    emit connectedChanged();
}
InteractiveSMTPServerWindow::InteractiveSMTPServerWindow( QTcpSocket * socket, QWidget * parent )
  : QWidget( parent ), mSocket( socket )
{
  QPushButton * but;
  Q_ASSERT( socket );

  QVBoxLayout * vlay = new QVBoxLayout( this );

  mTextEdit = new QTextEdit( this );
  vlay->addWidget( mTextEdit, 1 );
  QWidget *mLayoutWidget = new QWidget;
  vlay->addWidget( mLayoutWidget );

  QHBoxLayout * hlay = new QHBoxLayout( mLayoutWidget );
    
  mLineEdit = new QLineEdit( this );
  mLabel = new QLabel( "&Response:", this );
  mLabel->setBuddy( mLineEdit );
  but = new QPushButton( "&Send", this );
  hlay->addWidget( mLabel );
  hlay->addWidget( mLineEdit, 1 );
  hlay->addWidget( but );

  connect( mLineEdit, SIGNAL(returnPressed()), SLOT(slotSendResponse()) );
  connect( but, SIGNAL(clicked()), SLOT(slotSendResponse()) );

  but = new QPushButton( "&Close Connection", this );
  vlay->addWidget( but );

  connect( but, SIGNAL(clicked()), SLOT(slotConnectionClosed()) );

  connect( socket, SIGNAL(disconnected()), SLOT(slotConnectionClosed()) );
  connect( socket, SIGNAL(error(QAbstractSocket::SocketError)),
           SLOT(slotError(QAbstractSocket::SocketError)) );
  connect( socket, SIGNAL(readyRead()), SLOT(slotReadyRead()) );

  mLineEdit->setText( "220 hi there" );
  mLineEdit->setFocus();
}
//void TcpClientSocket::dataReceived(QString msg)
//{
////        emit updateClients(msg,msg.length());
//}
void TcpClientSocket::dataReceived(){
    QString name=this->readAll();
    if(isfirst==6666){
        qDebug()<<name;
        QStringList tmp=name.split(" ");
        if(q.Iscontent(tmp[0],tmp[2].toInt())){
            classname=tmp[2].toInt();
            if(classname>=3){
                return;
            }
            this->write("yes\n");
            this->write(q.getquestioncontent().toUtf8());
            this->flush();
            this->write(q.avaqueue(classname).toLatin1());
            this->flush();
            this->write("\nmdzz");
            this->flush();
        }else{
            this->write("no");
        }
        qDebug()<< "登陆 ";
    }else{
        qDebug() << "选题内容 " <<name;
        QStringList tmp=name.split("|");
        classname=tmp[2].toInt();
        qDebug() << classname;
        qDebug()<< tmp;
        if(q.selectquestion(tmp[0],classname,tmp[1].toInt())){
            this->write("OK");
            emit disconnected(this->socketDescriptor());
        }else{
            qDebug() << "error\n";
            this->write("error");
            this->write(q.avaqueue(classname).toLatin1());
            this->flush();
        }
        qDebug()<< "选题 ";
    }
}
/*!
  Constructs an assistant client with the specified \a parent. For
  systems other than Mac OS, \a path specifies the path to the Qt
  Assistant executable. For Mac OS, \a path specifies a directory
  containing a valid assistant.app bundle. If \a path is the empty
  string, the system path (\c{%PATH%} or \c $PATH) is used.
*/
QAssistantClient::QAssistantClient( const QString &path, QObject *parent )
    : QObject( parent ), host ( QLatin1String("localhost") )
{
#if defined(Q_OS_MAC)
    const QString assistant = QLatin1String("Assistant_adp");
#else
    const QString assistant = QLatin1String("assistant_adp");
#endif

    if ( path.isEmpty() )
        assistantCommand = assistant;
    else {
        QFileInfo fi( path );
        if ( fi.isDir() )
            assistantCommand = path + QLatin1String("/") + assistant;
        else
            assistantCommand = path;
    }

#if defined(Q_OS_MAC)
    assistantCommand += QLatin1String(".app/Contents/MacOS/Assistant_adp");
#endif

    socket = new QTcpSocket( this );
    connect( socket, SIGNAL(connected()),
            SLOT(socketConnected()) );
    connect( socket, SIGNAL(disconnected()),
            SLOT(socketConnectionClosed()) );
    connect( socket, SIGNAL(error(QAbstractSocket::SocketError)),
             SLOT(socketError()) );
    opened = false;
    proc = new QProcess( this );
    port = 0;
    pageBuffer = QLatin1String("");
    connect( proc, SIGNAL(readyReadStandardError()),
             this, SLOT(readStdError()) );
    connect( proc, SIGNAL(error(QProcess::ProcessError)),
        this, SLOT(procError(QProcess::ProcessError)) );
}
Exemple #9
0
bool QHttpSocketEngine::initialize(QAbstractSocket::SocketType type, QAbstractSocket::NetworkLayerProtocol protocol)
{
    Q_D(QHttpSocketEngine);
    if (type != QAbstractSocket::TcpSocket)
        return false;

    setProtocol(protocol);
    setSocketType(type);
    d->socket = new QTcpSocket(this);
#ifndef QT_NO_BEARERMANAGEMENT
    d->socket->setProperty("_q_networkSession", property("_q_networkSession"));
#endif

    // Explicitly disable proxying on the proxy socket itself to avoid
    // unwanted recursion.
    d->socket->setProxy(QNetworkProxy::NoProxy);

    // Intercept all the signals.
    connect(d->socket, SIGNAL(connected()),
            this, SLOT(slotSocketConnected()),
            Qt::DirectConnection);
    connect(d->socket, SIGNAL(disconnected()),
            this, SLOT(slotSocketDisconnected()),
            Qt::DirectConnection);
    connect(d->socket, SIGNAL(readyRead()),
            this, SLOT(slotSocketReadNotification()),
            Qt::DirectConnection);
    connect(d->socket, SIGNAL(bytesWritten(qint64)),
            this, SLOT(slotSocketBytesWritten()),
            Qt::DirectConnection);
    connect(d->socket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(slotSocketError(QAbstractSocket::SocketError)),
            Qt::DirectConnection);
    connect(d->socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this, SLOT(slotSocketStateChanged(QAbstractSocket::SocketState)),
            Qt::DirectConnection);

    return true;
}
Exemple #10
0
bool NetworkConnection::openConnection(const QString & host, const unsigned short port, bool not_main_connection)
{	
	qsocket = new QTcpSocket();	//try with no parent passed for now
	if(!qsocket)
		return 0;
	//connect signals
	
	//connect(qsocket, SIGNAL(hostFound()), SLOT(OnHostFound()));
	connect(qsocket, SIGNAL(connected()), SLOT(OnConnected()));
	connect(qsocket, SIGNAL(readyRead()), SLOT(OnReadyRead()));
	connect(qsocket, SIGNAL(disconnected ()), SLOT(OnConnectionClosed()));
//	connect(qsocket, SIGNAL(delayedCloseFinished()), SLOT(OnDelayedCloseFinish()));
//	connect(qsocket, SIGNAL(bytesWritten(qint64)), SLOT(OnBytesWritten(qint64)));
    connect(qsocket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(OnError(QAbstractSocket::SocketError)));

	if(qsocket->state() != QTcpSocket::UnconnectedState)
	{
		qDebug("Called openConnection while in state %d", qsocket->isValid());
		return 0;
	}
	//remove asserts later
	Q_ASSERT(host != 0);
	Q_ASSERT(port != 0);

	if(!not_main_connection)
		drawPleaseWait();

	qDebug("Connecting to %s %d...\n", host.toLatin1().constData(), port);
	// assume info.host is clean
	qsocket->connectToHost(host, (quint16) port);
	
	/* If dispatch does not have a UI, the thing that sets the UI
	 * will setupRoomAndConsole */
	/* Tricky now without dispatches... who sets up the UI?
	 * there's always a mainwindow... but maybe things aren't setup? */
	
	/* connectionInfo as a message with those pointers is probably a bad idea */
	return (qsocket->state() != QTcpSocket::UnconnectedState);
}
Exemple #11
0
void u3HClient::on_clientThread_Started()
{
	m_clientSocket = new QTcpSocket(this);
	if(m_clientSocket->setSocketDescriptor(m_socketDescriptor)) 
	{
		// when data ready to be read
		connect(m_clientSocket, SIGNAL(readyRead()), this, SLOT(on_clientSocket_DataReady()));
		connect(m_clientSocket, SIGNAL(disconnected()), this, SLOT(on_socketDisconnected()));

		packetBuilder *b = new packetBuilder(_hello, newclient);
		b->FinalizePacket();
		SendPacket(b);
	}
	else 
	{
		emit ClientFatalError(m_clientID, tr("Can't set descriptor on socket"));
		emit TerminateClient();
	}

	LogEvent("New client from : " + GetClientEndPointString());

}
void TestLocalSocket_Peer::onNewConnection(quintptr socketDescriptor)
{
	LocalServer	*	src	=	qobject_cast<LocalServer*>(sender());
	
	if(src == 0)
		return;
	
	QWriteLocker	locker(&m_socketLock);
	
	QVERIFY(m_socket == 0);
	
	m_socket	=	new LocalSocket(this);
	
	connect(m_socket, SIGNAL(socketDescriptorWritten(quintptr)), SLOT(fileDescriptorWritten(quintptr)));
	connect(m_socket, SIGNAL(disconnected()), SLOT(onDisconnected()), Qt::DirectConnection);
	
	m_socket->setSocketDescriptor(socketDescriptor);
	
	QVERIFY(m_socket->open(QIODevice::ReadWrite));
	
	m_socketChanged.wakeAll();
}
void NfcPeerToPeer::handleNewConnection()
{
    if (!m_connectServerSocket)
        return;

    if (m_nfcServerSocket) {
        m_nfcServerSocket->deleteLater();
    }

    // The socket is a child of the server and will therefore be deleted automatically
    m_nfcServerSocket = m_nfcServer->nextPendingConnection();

    connect(m_nfcServerSocket, SIGNAL(readyRead()), this, SLOT(readTextServer()));
    connect(m_nfcServerSocket, SIGNAL(error(QLlcpSocket::SocketError)), this, SLOT(serverSocketError(QLlcpSocket::SocketError)));
    connect(m_nfcServerSocket, SIGNAL(stateChanged(QLlcpSocket::SocketState)), this, SLOT(serverSocketStateChanged(QLlcpSocket::SocketState)));
    connect(m_nfcServerSocket, SIGNAL(disconnected()), this, SLOT(serverSocketDisconnected()));

    if (m_reportingLevel != AppSettings::OnlyImportantReporting) {
        emit statusMessage("New server socket connection");
    }
    sendCachedText();
}
Exemple #14
0
//----------------------------------------------------------------------------//
// QCanConfig()                                                                 //
// constructor                                                                //
//----------------------------------------------------------------------------//
QCanConfig::QCanConfig(QObject *parent) :
    QObject(parent)
{
   //----------------------------------------------------------------
   // get the instance of the main application
   //
   pclAppP = QCoreApplication::instance();

   
   //----------------------------------------------------------------
   // connect signals for socket operations
   //
   QObject::connect(&clCanSocketP, SIGNAL(connected()),
                    this, SLOT(socketConnected()));

   QObject::connect(&clCanSocketP, SIGNAL(disconnected()),
                    this, SLOT(socketDisconnected()));
   
   QObject::connect(&clCanSocketP, SIGNAL(error(QAbstractSocket::SocketError)),
                    this, SLOT(socketError(QAbstractSocket::SocketError)));
   
}
Exemple #15
0
//! [4]
void Server::sendFortune()
{
//! [5]
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
//! [4] //! [6]
    out << (quint16)0;
    out << fortunes.at(qrand() % fortunes.size());
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));
//! [6] //! [7]

    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()),
            clientConnection, SLOT(deleteLater()));
//! [7] //! [8]

    clientConnection->write(block);
    clientConnection->disconnectFromHost();
//! [5]
}
Exemple #16
0
void SkpSocketTestWidget::skp_on_timer_socket()
{
    int threadIndex = m_connectNumber % THREAD_NUMBER;
    QThread *thread = m_threadList.at(threadIndex);
    m_connectNumber++;

    SkpTcpSocketTest *tcpSocketTest = new SkpTcpSocketTest();

    connect(tcpSocketTest, SIGNAL(connected()), tcpSocketTest, SLOT(skp_on_connect()));
    connect(tcpSocketTest, SIGNAL(readyRead()), tcpSocketTest, SLOT(skp_on_read()));
    connect(tcpSocketTest, SIGNAL(disconnected()), tcpSocketTest, SLOT(skp_on_disconnected()));
    connect(tcpSocketTest, SIGNAL(error(QAbstractSocket::SocketError)),
            tcpSocketTest, SLOT(skp_on_error(QAbstractSocket::SocketError)));

    connect(tcpSocketTest, SIGNAL(skp_sig_quit(qint64, qint64, qint64, qint64)), this, SLOT(skp_on_quit(qint64, qint64, qint64, qint64)));
    connect(tcpSocketTest, SIGNAL(skp_sig_socket_quit(qint64, qint64, qint64, qint64)), this, SLOT(skp_on_socket_quit(qint64, qint64, qint64, qint64)));

    tcpSocketTest->connectToHost(connectIP, connectPort);
    tcpSocketTest->waitForConnected();

    tcpSocketTest->moveToThread(thread);
}
void SockClient::readhandler(){
    int n;
    const int buflen = bufferSize;
    char buffer[buflen];
    CharString writeto;
    
    Logger::GLOBAL.log("[SockClient]  reading thread started");
    
    while(alive){
        
        n = read(sockd, buffer, buflen);
        if (n < 0){
            std::this_thread::sleep_for(std::chrono::milliseconds(5));
            continue;
        }else if(n==0){
            Logger::GLOBAL.log("[SockClient] disconnected from server");
            if(disconnected != 0x0) disconnected(server, this);
            alive = false;
            return;
        }
        
        // post-clear extra data in packet... (Prevents extra cpu usage, clearer data stream)
        for(int i=n-1;i<buflen;i++) buffer[i] = 0;

        if(_clientHandler != 0x0 && n > 1) {
            //CharString d = (server->decryptor!=0x0) ? server->decryptor(CharString(buffer,n)) : CharString(buffer,n); // decrypt
            CharString d = CharString(buffer,n); // decrypt
            _clientHandler(d, writeto, this, exVAL);

            if(writeto.getSize() > 0){
                // segment packet if it is too large.
                sendc(writeto); // encryption in-client
            }
        }
    }
    
    Logger::GLOBAL.log("[SockClient] reading thread ended");
    alive = false;
}
Connection::Connection(QTcpSocket *socket, Server *server)
 : QObject(0), m_socket(socket), m_server(server)
{
  qDebug() << "Connection::Connection()";

  if (! m_socket) {
    qDebug() << "No socket.";
    return;
  }

  if (! m_server) {
    qDebug() << "No server.";
    return;
  }

  QObject::connect(socket, SIGNAL(disconnected()),
                   socket, SLOT(deleteLater()));

  m_close_connection = false;                              // Connection is initially open.
  m_byte_order       = QDataStream::BigEndian;             // Most significant byte first (the default).
  m_sequence_number  = 0;
}
Exemple #19
0
//================================================================================================================================
SocketClass::SocketClass(QTcpSocket *tcpSocket, QObject *parent, int timeOut,  bool terminalkoMode) :
    QObject(parent)
{
    this->terminalkoMode = terminalkoMode;
    this->tcpSocket = tcpSocket;
    this->timeOut = timeOut;
    connect(this->tcpSocket, SIGNAL(readyRead()), this, SLOT(mReadyRead()) );
    connect(this->tcpSocket, SIGNAL(disconnected()), this, SLOT(tellAboutDisConnection()) ); //SLOT(deleteLater()) );
    loclalAddrs = this->tcpSocket->peerAddress().toString();
   loclalAddrsLong = loclalAddrs;

    while(loclalAddrsLong.length() < 15){
        loclalAddrsLong.prepend(" ");
        if(loclalAddrsLong.length() < 15)
            loclalAddrsLong.append(" ");
        else
            break;
    }

//    if(!terminalkoMode)
    QTimer::singleShot(1, this, SLOT(tellAboutConnection()) );
}
void QLocalSocketPrivate::setErrorString(const QString &function)
{
    Q_Q(QLocalSocket);
    BOOL windowsError = GetLastError();
    QLocalSocket::LocalSocketState currentState = state;

    // If the connectToServer fails due to WaitNamedPipe() time-out, assume ConnectionError  
    if (state == QLocalSocket::ConnectingState && windowsError == ERROR_SEM_TIMEOUT)
        windowsError = ERROR_NO_DATA;

    switch (windowsError) {
    case ERROR_PIPE_NOT_CONNECTED:
    case ERROR_BROKEN_PIPE:
    case ERROR_NO_DATA:
        error = QLocalSocket::ConnectionError;
        errorString = QLocalSocket::tr("%1: Connection error").arg(function);
        state = QLocalSocket::UnconnectedState;
        break;
    case ERROR_FILE_NOT_FOUND:
        error = QLocalSocket::ServerNotFoundError;
        errorString = QLocalSocket::tr("%1: Invalid name").arg(function);
        state = QLocalSocket::UnconnectedState;
        break;
    default:
        error = QLocalSocket::UnknownSocketError;
        errorString = QLocalSocket::tr("%1: Unknown error %2").arg(function).arg(windowsError);
#if defined QLOCALSOCKET_DEBUG
        qWarning() << "QLocalSocket error not handled:" << errorString;
#endif
        state = QLocalSocket::UnconnectedState;
    }

    if (currentState != state) {
        q->emit stateChanged(state);
        if (state == QLocalSocket::UnconnectedState)
            q->emit disconnected();
    }
    emit q->error(error);
}
Exemple #21
0
pSocket::pSocket(QTcpSocket *socket, QThread *thread, QAtomicInt& limit) :
    QObject(0), _socket(socket), _packetSize(0), _limit(limit)
{
    connect(_socket, SIGNAL(readyRead()), this, SLOT(onDataReceived()));
    connect(_socket, SIGNAL(disconnected()), this, SLOT(deleteLater()));
//    connect(_socket, SIGNAL(disconnected()), _socket, SLOT(deleteLater()));
    connect(this, SIGNAL(saveFile(QByteArray,QString)), pSaver::inst(), SLOT(save(QByteArray,QString)));

    _socket->setParent(this);
    moveToThread(thread);

#ifdef FUNC_DEBUG
    qDebug() << '\n' << Q_FUNC_INFO << "New connection" << socket->localAddress();
#endif

#ifdef TIME_DEBUG
    if (!dTime) {
        dTime = new QTime;
        dTime->start();
    }
#endif
}
ControllerPage::ControllerPage(SetupWizard *wizard, QWidget *parent) :
    AbstractWizardPage(wizard, parent),
    ui(new Ui::ControllerPage)
{
    ui->setupUi(this);

    m_connectionManager = getWizard()->getConnectionManager();
    Q_ASSERT(m_connectionManager);
    connect(m_connectionManager, SIGNAL(availableDevicesChanged(QLinkedList<Core::DevListItem>)), this, SLOT(devicesChanged(QLinkedList<Core::DevListItem>)));

    ExtensionSystem::PluginManager *pluginManager = ExtensionSystem::PluginManager::instance();
    Q_ASSERT(pluginManager);
    m_telemtryManager = pluginManager->getObject<TelemetryManager>();
    Q_ASSERT(m_telemtryManager);
    connect(m_telemtryManager, SIGNAL(connected()), this, SLOT(connectionStatusChanged()));
    connect(m_telemtryManager, SIGNAL(disconnected()), this, SLOT(connectionStatusChanged()));

    connect(ui->connectButton, SIGNAL(clicked()), this, SLOT(connectDisconnect()));

    setupBoardTypes();
    setupDeviceList();
}
	/// \brief Initializes the command buffers and lists.
	/// \param parent The parent widget.
	Control::Control(QObject *parent) : DsoControl(parent) {
		// Values for the Gain and Timebase enums
		gainSteps << 0.500 << 1.000 << 2.000 << 5.000 << 10.00; // in fullrange Volts
		samplerateChannelMax = 48e6;
		samplerateFastMax = 48e6;
		samplerateMax = samplerateChannelMax;
		samplerateDivider = 1;
        bufferMulti = 1;
		triggerPosition = 0;
		triggerSlope = Dso::SLOPE_POSITIVE;
		triggerSpecial = false;
		triggerSource = 0;
		triggerPoint = 0;

		// Channel level data
		for (unsigned int channel = 0; channel < BUUDAI_CHANNELS; channel++) {
			for (unsigned int gainId = 0; gainId < GAIN_COUNT; gainId++) {
				channelLevels[channel][gainId]= 0x0000;
			}
			sampleRange[channel] = 255;
			gain[channel] = GAIN_500MV;
		}

		offsetReal[0] = double(136)/sampleRange[0];
		offsetReal[1] = double(132)/sampleRange[1];
		cal[0] = 1.18;
		cal[1] = 1.21;

		// USB device
		device = new Device(this);
		
		// Sample buffers
		for (unsigned int channel = 0; channel < BUUDAI_CHANNELS; channel++) {
            samples.append(0);
            samplesSize.append(0);
		}
		
		connect(device, SIGNAL(disconnected()), this, SLOT(disconnectDevice()));
	}
Exemple #24
0
void QNetworkAccessDebugPipeBackend::socketError()
{
    QNetworkReply::NetworkError code;
    switch (socket.error()) {
    case QAbstractSocket::RemoteHostClosedError:
        return;                 // socketDisconnected will be called

    case QAbstractSocket::NetworkError:
        code = QNetworkReply::UnknownNetworkError;
        break;

    default:
        code = QNetworkReply::ProtocolFailure;
        break;
    }

    error(code, QObject::tr("Socket error on %1: %2")
          .arg(url().toString(), socket.errorString()));
    finished();
    disconnect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));

}
static void handle_event(nge_event * e)
{
	switch (e->state_type) {
	case SERVICE_STATE_CHANGE:
		service_change(e->payload.service_state_change.service,
			       e->payload.service_state_change.is,
			       e->payload.service_state_change.state_name,
			       e->payload.service_state_change.percent_started,
			       e->payload.service_state_change.percent_stopped,
			       e->payload.service_state_change.service_type,
			       e->payload.service_state_change.hidden);
		return;
	case SYSTEM_STATE_CHANGE:
		sys_state(e->payload.system_state_change.system_state,
			  e->payload.system_state_change.runlevel);
		return;
	case ERR_MSG:
		err_msg(e->payload.err_msg.mt,
			e->payload.err_msg.file,
			e->payload.err_msg.func,
			e->payload.err_msg.line, e->payload.err_msg.message);
		return;
	case CONNECT:
		connected(e->payload.connect.pver,
			  e->payload.connect.initng_version);
		return;
	case DISCONNECT:
		disconnected();
		return;
	case SERVICE_OUTPUT:
		service_output(e->payload.service_output.service,
			       e->payload.service_output.process,
			       e->payload.service_output.output);
		return;
	default:
		return;
	}
}
  void SocksConnection::StartUdpAssociate(const SocksHostAddress &peer_host)
  {
    if(!peer_host.IsHostName() 
        && peer_host.GetPort() 
        && peer_host.GetAddress() != QHostAddress::Any 
        && peer_host.GetAddress() != QHostAddress::AnyIPv6) {
      _udp_peer = peer_host.GetAddress();
      _udp_peer_port = peer_host.GetPort();
    }

    _udp_socket = QSharedPointer<QUdpSocket>(new QUdpSocket());
    // Bind to some accessible port on the same address as the
    // SOCKS TCP server 
    _udp_socket->bind(_socket->localAddress(), 0);
    
    if(_udp_socket->state() != QAbstractSocket::BoundState) {
      return EstablishFail(SocksReply_GeneralServerFailure);
    }
    
    // Connect to methods here
    connect(_udp_socket.data(), SIGNAL(readyRead()), this, SLOT(UdpReadFromSocket()));
    connect(_udp_socket.data(), SIGNAL(disconnected()), this, SLOT(Close()));
    connect(_udp_socket.data(), SIGNAL(error(QAbstractSocket::SocketError)), 
             SLOT(UdpHandleError(QAbstractSocket::SocketError)));

    QByteArray verif_bytes = _verif_key->GetByteArray();
    QByteArray packet = UdpStartPacket(verif_bytes).ToByteArray();

    // Start the connection
    _conn_id = _hash_algo->ComputeHash(verif_bytes);
    emit ProxyConnected();
    _state = ConnState_Connected;

    SendUpstreamPacket(packet); 

    qDebug() << "SOCKS UDP Addr" << _udp_socket->localAddress() << _udp_socket->localPort();
    SocksConnection::WriteSocksReply(SocksReply_Succeeded, _udp_socket->localAddress(), _udp_socket->localPort());
  }
Exemple #27
0
void QtLocalPeer::receiveConnection()
{
    QLocalSocket* socket = server->nextPendingConnection();
    if (!socket)
        return;

    int client_id = this->client_seq ++;
    this->clients.insert(socket, client_id);
    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));
    QObject::connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));

    return; 
    // multi client long connection support
    while (socket->bytesAvailable() < (int)sizeof(quint32))
        socket->waitForReadyRead();
    QDataStream ds(socket);
    QByteArray uMsg;
    quint32 remaining;
    ds >> remaining;
    uMsg.resize(remaining);
    int got = 0;
    char* uMsgBuf = uMsg.data();
    do {
        got = ds.readRawData(uMsgBuf, remaining);
        remaining -= got;
        uMsgBuf += got;
    } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
    if (got < 0) {
        qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
        delete socket;
        return;
    }
    QString message(QString::fromUtf8(uMsg));
    socket->write(ack, qstrlen(ack));
    socket->waitForBytesWritten(1000);
    // delete socket;
    emit messageReceived(message); //### (might take a long time to return)
}
Exemple #28
0
  void server::send_intf_info() const
  {
    std::vector<std::string> interface_strings = control_.interface_info();

    QByteArray block;
    QDataStream out(&block,QIODevice::WriteOnly);

    out.setVersion(QDataStream::Qt_5_0);

    // mark the beginning of the block
    out << (quint16)0;

    // stream interface info strings in block
    for(unsigned short index = 0 ; index < interface_strings.size() ; ++index)
    {
      out << interface_strings[index].c_str();
    }

    // set index back to the beginning of the block
    out.device()->seek(0);
    // stream block size in
    out << (quint16)(block.size() - sizeof(quint16));


    // get actual connection
    QLocalSocket * client_connection =

    intf_info_server->nextPendingConnection();

    // register destruction of connection after usage
    connect(client_connection , SIGNAL(disconnected()),
            client_connection , SLOT(deleteLater())    );


    client_connection->write(block);
    client_connection->flush();
    client_connection->disconnectFromServer();
  }
Exemple #29
0
    /**
      * Appelé quand un client se connecte au serveur.
      * Envoie la connexion au serveur si celle-ci
      * n'est pas filtrée
      */
    void ClientHandler::handleIncomming()
    {
        //On recupère le socket server
        QTcpServer *server = qobject_cast<QTcpServer*>(sender());
        //Si ce n'est pas un socket qui a envoyé
        if (server == NULL)
        {
            qDebug() << "ClientHandler::handleIncomming: Erreur, socket serveur incorrect";
            return;
        }
        //On recupère la socket
        QTcpSocket *socket = server->nextPendingConnection();
        //Si la socket n'existe pas, on retourne
        if (socket == NULL)
        {
            return;
        }
        //On indique qu'un client s'est connecté.
        qDebug() << "Nouvelle connexion en provenance de " << socket->peerAddress().toString();
        //Sinon, on procède à des vérifications

        //On vérifie que le nombre maximal de joueurs n'est pas atteint
        if (getClientsOnline() >= _maxPlayers)
        {
            //On affiche un message dans la console
            qDebug() << "Trop de joueurs dans le serveur.";
            //On deconnecte le client
            socket->close();

            return;
        }
        //TODO: Programmer la véfification du client.

        //On connecte le signal pour la deconnexion
        connect(socket,SIGNAL(disconnected()),this,SLOT(handleDisconnection()));
        //On envoie le signal pour dire qu'il y'a un nouveau client
        emit newClient(socket);
    }
Exemple #30
0
bool SignalProxy::addPeer(QIODevice* iodev) {
  if(!iodev)
    return false;

  if(_peers.contains(iodev))
    return true;

  if(proxyMode() == Client && !_peers.isEmpty()) {
    qWarning("SignalProxy: only one peer allowed in client mode!");
    return false;
  }

  if(!iodev->isOpen()) {
    qWarning("SignalProxy::addPeer(QIODevice *iodev): iodev needs to be open!");
    return false;
  }

  connect(iodev, SIGNAL(disconnected()), this, SLOT(removePeerBySender()));
  connect(iodev, SIGNAL(readyRead()), this, SLOT(dataAvailable()));

#ifdef HAVE_SSL
  QSslSocket *sslSocket = qobject_cast<QSslSocket *>(iodev);
  if(sslSocket) {
    connect(iodev, SIGNAL(encrypted()), this, SLOT(updateSecureState()));
  }
#endif

  if(!iodev->parent())
    iodev->setParent(this);

  _peers[iodev] = new IODevicePeer(iodev, iodev->property("UseCompression").toBool());

  if(_peers.count() == 1)
    emit connected();

  updateSecureState();
  return true;
}