Ejemplo n.º 1
0
//get user information and pass into thread
void AwesumeClient::on_btnConnect_clicked()
{
    if (ui->btnConnect->text() == "Connect")
    {
        QString hostname = ui->hostname->text();
        QString user = ui->username->text();
        QString password = ui->password->text();

        thread = new ConnectThread(hostname, user, password);
        connect(thread, SIGNAL(finished()), this, SLOT(connectFinished()));
        thread->start();

        ui->btnConnect->setText("Disconnect");
    }
    else if (ui->btnConnect->text() == "Disconnect")
    {
        serverDisconnected();
        ui->btnConnect->setText("Connect");
        ui->hostname->clear();
        ui->username->clear();
        ui->password->clear();
    }

    SCORE->setInterval(100);
    connect(SCORE, &QTimer::timeout, this, &AwesumeClient::timerHit);
    SCORE->start();
}
Ejemplo n.º 2
0
bool YapClient::sendSyncCommand()
{
    char pktHeader[4] = { 0, 0, 0, 0 };
    uint16_t pktLen;
    char * ppp = 0;

    if (d->cmdPacket->length() == 0) {
        fprintf(stderr, "Command is empty\n");
        return false;
    }

    pktLen = 0;
    ::memset(pktHeader, 0, sizeof(pktHeader));

    pktLen = d->cmdPacket->length();
    pktLen = bswap_16(pktLen);
    ::memcpy(pktHeader, &pktLen, 2);
    pktHeader[3] = kPacketFlagSyncMask;

    if (!writeSocket(d->cmdSocketFd, pktHeader, 4))
        goto Detached;

    if (!writeSocket(d->cmdSocketFd, (char*) d->cmdBuffer, d->cmdPacket->length()))
        goto Detached;


    pktLen = 0;
    ::memset(pktHeader, 0, sizeof(pktHeader));

    if (!readSocketSync(d->cmdSocketFd, pktHeader, 4))
        goto Detached;

    ppp = ((char *)&pktHeader[0]);
    pktLen   = *((uint16_t*) ppp);
    pktLen   = bswap_16(pktLen);
    if (pktLen > kMaxMsgLen) {
        fprintf(stderr, "YAP: Message too large %u > %u\n", pktLen, kMaxMsgLen);
        goto Detached;
    }

    if (!readSocketSync(d->cmdSocketFd, (char*) d->replyBuffer, pktLen))
        goto Detached;

    d->replyPacket->reset();
    d->replyPacket->setReadTotalLength(pktLen);

    return true;

 Detached:

    serverDisconnected();
    closeMsgSocket();
    closeCmdSocket();

    return false;
}
ClientControllerWidget::ClientControllerWidget(Client *client, QWidget *parent, Qt::WindowFlags f) :
  QWidget(parent, f),
  _client(client)
{
  _ui.setupUi(this);
  _ui.savePath->setObjectName(QDir::homePath());
  _ui.filesView->setModel(new ClientFilesModel(_client, this));
  connect(_ui.savePathButton, SIGNAL(clicked()), SLOT(onSavePathButtonClicked()));
  connect(_client, SIGNAL(serverConnected()), SLOT(updateGuiState()));
  connect(_client, SIGNAL(serverDisconnected()), SLOT(updateGuiState()));
}
Ejemplo n.º 4
0
Client::Client(QObject *parent) :
  QObject(parent),
  _serverConnection(0)
{
  qRegisterMetaType<QHostAddress>("QHostAddress");

  _serverConnection = new ClientServerConnectionHandler(this, this);
  connect(_serverConnection->getSocket(), SIGNAL(connected()), SIGNAL(serverConnected()));
  connect(_serverConnection->getSocket(), SIGNAL(disconnected()), SIGNAL(serverDisconnected()));

  _dataSocket = new ClientUdpSocket(this, this);
}
Ejemplo n.º 5
0
bool TCPNetworkServer::connectToServer(const QString &sAddress, int port)
{
	clientConnectionSocket = new QTcpSocket(this);
	clientConnectionSocket->abort();
	clientConnectionSocket->connectToHost(sAddress, (quint16)port);
	clientConnectionSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
	clientConnectionSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);

	connect(clientConnectionSocket, SIGNAL(disconnected()), this, SLOT(serverDisconnected()));
	connect(clientConnectionSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(serverErrorNetworkData(QAbstractSocket::SocketError)));
	return connect(clientConnectionSocket, SIGNAL(readyRead()), this, SLOT(dataFromServerAvailable()));
}
Ejemplo n.º 6
0
void PingPong::addService(const QBluetoothServiceInfo &service)
{
    setMessage("Service found. Setting parameters...");
    //! [Connecting the socket]
    socket = new QBluetoothSocket(QBluetoothServiceInfo::L2capProtocol);
    socket->connectToService(service);

    connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket()));
    connect(socket, SIGNAL(connected()), this, SLOT(serverConnected()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(serverDisconnected()));
    //! [Connecting the socket]
    m_serviceFound = true;
}
Ejemplo n.º 7
0
void INDI::BaseClientQt::processSocketError( QAbstractSocket::SocketError socketError )
{
    if (sConnected == false)
        return;

    // TODO Handle what happens on socket failure!
    INDI_UNUSED(socketError);
    IDLog("Socket Error: %s\n", client_socket.errorString().toLatin1().constData());
    fprintf (stderr,"INDI server %s/%d disconnected.\n", cServer.c_str(), cPort);
    delLilXML(lillp);
    client_socket.close();
    // Let client handle server disconnection
    serverDisconnected(-1);
}
Ejemplo n.º 8
0
NetworkManager::NetworkManager(QString host, int port, QObject *parent) : JsonCommunication(host, port, parent)
{
    m_logged = false;

    m_heartbeatManager = new HeartbeatManager(3,this);
        connect(m_heartbeatManager, SIGNAL(networkRequest(QString)), this, SLOT(serverRequest(QString)));
        connect(m_heartbeatManager, SIGNAL(queueFull()), this, SLOT(forceDisconnect()));
        connect(this,SIGNAL(connectedChanged(bool)),m_heartbeatManager,SLOT(setRunning(bool)));
        connect(this,SIGNAL(hearthbeatReceived(QString)),m_heartbeatManager,SLOT(validate(QString)));

    connect(this,SIGNAL(jsonReceived(QString)),this,SLOT(processJson(QString)));
    connect(this,SIGNAL(serverConnected()),this,SLOT(tryLogin()));
    connect(this,SIGNAL(serverDisconnected()),this,SLOT(setNotLogged()));
}
Ejemplo n.º 9
0
void WaveformClient::connectToServer() {
	std::cout << "in WaveformClient connect to server" << std::endl;
	blockSize = 0;
	try {
        tcpSocket = new QTcpSocket(this);
        connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));
		connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(serverDisconnected()));
		tcpSocket->connectToHost(hostLine->text(),portLine->text().toInt());

		connectButton->setEnabled(false);
	}
	catch (std::exception& e)
	{
	    std::cerr << "Exception: " << e.what() << "\n";
	}
	std::cout << "finished connect to server" << std::endl;
}
void LoginService::create() {
	if (!m_parser)
		m_parser = new OscarParser();

	m_st1 = new LoginSt1Process(this, m_uin, m_pass);

	// Parser && LoginSt1Process conn
	QObject::connect(m_parser, SIGNAL(recvHello()), m_st1, SLOT(recvHello()));
	QObject::connect(m_parser, SIGNAL(receivedBOS(QString, QString, QByteArray)), m_st1, SLOT(recvBOS(QString, QString, QByteArray)));

	// Service && LoginSt1Process conn
	QObject::connect(m_st1, SIGNAL(stage1finished(QString, QString, QByteArray)), this, SLOT(getBOSInfo(QString, QString, QByteArray)), Qt::DirectConnection);

	// Parser && LoginSt1Process conn
	QObject::connect(m_parser, SIGNAL(serverDisconnected(QString, DisconnectReason)), 
				this, SLOT(unexpectedDisconnect(QString, DisconnectReason)));
}
Ejemplo n.º 11
0
//handle connecting to server
void AwesumeClient::connectFinished()
{
    success = thread->getResult();
    QString errorMsg = thread->getMsg();
    if (success == true)
    {
        socket = thread->getSocket();
        connect(socket, SIGNAL(readyRead()), this, SLOT(dataReceived()));
        connect(socket, SIGNAL(disconnected()), this, SLOT(serverDisconnected()));
        QMessageBox::information(this, "Connection", errorMsg);
        ui->btnSend->setEnabled(true);
    }
    else
    {
        QMessageBox::warning(this, "Uh oh", errorMsg);
    }

}
Ejemplo n.º 12
0
int Server::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QWidget::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: readyToSendData(); break;
        case 1: messageReceived((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 2: serverDisconnected(); break;
        case 3: acceptConnection(); break;
        case 4: connectionAccepted(); break;
        case 5: readDataFromClient(); break;
        case 6: sslErrors((*reinterpret_cast< const QList<QSslError>(*)>(_a[1]))); break;
        case 7: notifyDisconnect(); break;
        }
        _id -= 8;
    }
    return _id;
}
Ejemplo n.º 13
0
CMainWindow::CMainWindow(int argc, char *argv[], QWidget *parent)
    : QMainWindow(parent)
{
    //======================================================================================================================================
    QStringList arguments;

    for (int i = 0; i < argc; i++)
    {
        arguments.append(argv[i]);

        arguments[i].remove("-");
    }
    //======================================================================================================================================
    qSetMessagePattern("[%{time h:mm:ss:zzz} %{if-category}%{category}%{endif} %{type}] %{function}: - %{message}");
    //======================================================================================================================================
    ui.setupUi(this);
    QSettings settings;
    m_EventFilter = CEventFilter::Signleton();
    m_Data = new CData;
    //======================================================================================================================================
    if (arguments.contains("ip"))
    {
        m_WebSocketClient = new CWebSocketClient(QUrl(QString("ws://%1").arg((arguments.at(arguments.indexOf("ip") + 1)))), m_Data);
        settings.setValue("IPAdress", arguments.at(arguments.indexOf("ip") + 1).split(":").first());
        settings.setValue("Port", arguments.at(arguments.indexOf("ip") + 1).split(":").last());
    }
    else
        m_WebSocketClient = new CWebSocketClient(QUrl(QString("ws://%1:%2").arg(settings.value("IPAdress").toString()).arg(settings.value("Port").toString())), m_Data);
    //======================================================================================================================================
    ////Actions
    //QAction *action_Close = new QAction(QIcon(QString::fromUtf8(":/Resources/cancel.png")), "Close", this);
    //QAction *action_FullScreen = new QAction(QIcon(QString::fromUtf8(":/Resources/slideshow_full_screen.png")), "Fullsreen", this);
    //QAction *action_HomePage = new QAction(QIcon(QString::fromUtf8(":/Resources/home_page.png")), "Home Page", this);
    //QAction *action_Plotter = new QAction(QIcon(QString::fromUtf8(":/Resources/chart_curve.png")), "Plotter", this);
    ////======================================================================================================================================
    ////Toolbar
    //ui.toolBar->addAction(action_Close);
    //ui.toolBar->addAction(action_FullScreen);
    //ui.toolBar->addSeparator();
    //ui.toolBar->setIconSize(QSize(20, 20));
    //ui.toolBar->addAction(action_HomePage);
    //ui.toolBar->addAction(action_Plotter);
    //======================================================================================================================================
    //StartPage
    m_StartPage = new CStartPage(this);
    ui.stackedWidget->addWidget(m_StartPage->getView());
    //======================================================================================================================================
    //Plotter
    m_Plotter = new CPlotter(this);
    ui.stackedWidget->addWidget(m_Plotter->getView());
    //======================================================================================================================================
    //Settings
    m_Settings = new CSettings(this);
    ui.stackedWidget->addWidget(m_Settings);
    //======================================================================================================================================
    //======================================================================================================================================
    connect(m_EventFilter,		SIGNAL(reciveClick()),							this,		SLOT(showNextPage()));
    connect(m_EventFilter,		SIGNAL(reciveDoubleClick()),					this,		SLOT(showSettings()));

    connect(m_Data,				SIGNAL(NewDataRecieved()),						this,		SLOT(onNewData()));

    connect(m_Settings,			SIGNAL(reciveNewURL(QString)),					this,		SLOT(onNewURL(QString)));
    connect(m_Settings,			SIGNAL(ready()),								this,		SLOT(showStartpage()));

    connect(m_WebSocketClient,	SIGNAL(serverConnected(QString)),				m_Settings, SLOT(onServerConnected(QString)));
    connect(m_WebSocketClient,	SIGNAL(serverDisconnected()),					m_Settings, SLOT(onServerDisconnected()));

    connect(m_WebSocketClient,	SIGNAL(recievedInitialScript(QJsonObject)),		m_Data,		SLOT(recievedInitialScript(QJsonObject)));
    connect(m_WebSocketClient,	SIGNAL(recievedDataScript(QJsonObject)),		m_Data,		SLOT(recievedDataScript(QJsonObject)));

    //======================================================================================================================================
    //======================================================================================================================================
    resize(480, 320);

    ui.stackedWidget->setCurrentIndex(0);
}
Ejemplo n.º 14
0
void Server :: notifyDisconnect()
 {
  connected=0;
  emit serverDisconnected();
 }
Ejemplo n.º 15
0
Tennis::Tennis(QWidget *parent)
: QDialog(parent), ui(new Ui_Tennis), board(new Board), controller(new Controller), socket(0),
  m_discoveryAgent(new QBluetoothServiceDiscoveryAgent), m_handover(0)
{
    // start Bluetooth if not started
    QBluetoothLocalDevice *device = new QBluetoothLocalDevice();
    device->powerOn();
    delete device;
    device = 0;

    //! [Construct UI]
    ui->setupUi(this);

    isClient = false;
    isConnected = false;
    quickDiscovery = true;

#if defined (Q_OS_SYMBIAN) || defined(Q_OS_WINCE) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
    setWindowState(Qt::WindowMaximized);
#endif

    ui->pongView->setScene(board->getScene());    

    connect(ui->pongView, SIGNAL(mouseMove(int, int)), this, SLOT(mouseMove(int, int)));
    ui->pongView->setMouseTracking(false);

    connect(board, SIGNAL(ballCollision(Board::Edge)), controller, SLOT(ballCollision(Board::Edge)));
    connect(board, SIGNAL(scored(Board::Edge)), controller, SLOT(scored(Board::Edge)));
    connect(controller, SIGNAL(moveBall(int,int)), board, SLOT(setBall(int,int)));
    connect(this, SIGNAL(moveLeftPaddle(int)), board, SLOT(setLeftPaddle(int)));
    connect(this, SIGNAL(moveRightPaddle(int)), board, SLOT(setRightPaddle(int)));
    connect(controller, SIGNAL(score(int,int)), board, SLOT(setScore(int,int)));
    connect(controller, SIGNAL(fps(const QString&)), this, SLOT(fps(const QString&)));

    setFocusPolicy(Qt::WheelFocus);

    paddle_pos = (Board::Height-12)/2-Board::Paddle/2;
    endPaddlePos = paddle_pos;

    emit moveLeftPaddle(paddle_pos);
    board->setRightPaddle(paddle_pos);

    server = new TennisServer(this);

    connect(controller, SIGNAL(moveBall(int,int)), server, SLOT(moveBall(int,int)));
    connect(controller, SIGNAL(score(int,int)), server, SLOT(score(int,int)));
    connect(this, SIGNAL(moveLeftPaddle(int)), server, SLOT(moveLeftPaddle(int)));
    connect(server, SIGNAL(clientConnected(QString)), this, SLOT(serverConnected(QString)));
    connect(server, SIGNAL(clientDisconnected(QString)), this, SLOT(serverDisconnected()));
    connect(server, SIGNAL(moveRightPaddle(int)), board, SLOT(setRightPaddle(int)));
    connect(server, SIGNAL(lag(int)), this, SLOT(lagReport(int)));

    connect(server, SIGNAL(clientConnected(QString)), controller, SLOT(refresh()));

    server->startServer();

    client = new TennisClient(this);

    connect(client, SIGNAL(moveBall(int,int)), board, SLOT(setBall(int,int)));
    connect(client, SIGNAL(moveLeftPaddle(int)), board, SLOT(setLeftPaddle(int)));
    connect(client, SIGNAL(connected(QString)), this, SLOT(clientConnected(QString)));
    connect(client, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
    connect(this, SIGNAL(moveRightPaddle(int)), client, SLOT(moveRightPaddle(int)));
    connect(client, SIGNAL(score(int,int)), board, SLOT(setScore(int,int)));
    connect(client, SIGNAL(lag(int)), this, SLOT(lagReport(int)));

    connect(this, SIGNAL(moveLeftPaddle(int)), controller, SLOT(moveLeftPaddle(int)));
    connect(this, SIGNAL(moveRightPaddle(int)), controller, SLOT(moveRightPaddle(int)));
    connect(server, SIGNAL(moveRightPaddle(int)), controller, SLOT(moveRightPaddle(int)));


//    ui->pongView->setBackgroundBrush(QBrush(Qt::white));
    ui->pongView->setCacheMode(QGraphicsView::CacheBackground);

    QNearFieldManager nearFieldManager;
    if (nearFieldManager.isAvailable()) {
        m_handover = new Handover(server->serverPort(), this);
        connect(m_handover, SIGNAL(bluetoothServiceChanged()), this, SLOT(nearFieldHandover()));

        connect(m_discoveryAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)),
                this, SLOT(serviceDiscovered(QBluetoothServiceInfo)));
        connect(m_discoveryAgent, SIGNAL(finished()), this, SLOT(discoveryFinished()));
    }


    m_discoveryAgent->setUuidFilter(QBluetoothUuid(serviceUuid));


    QString address;
    QString port;
    QStringList args = QCoreApplication::arguments();
    if(args.length() >= 2){
        address = args.at(1);
        if(args.length() >= 3){
            port = args.at(2);
        }
    }

    if(address.isEmpty()){
        QSettings settings("QtDF", "bttennis");
        address = settings.value("lastclient").toString();
    }

    if(!address.isEmpty()){
        qDebug() << "Connect to" << address << port;
        QBluetoothDeviceInfo device = QBluetoothDeviceInfo(QBluetoothAddress(address), "", QBluetoothDeviceInfo::ComputerDevice);
        QBluetoothServiceInfo service;
        if (!port.isEmpty()) {
            QBluetoothServiceInfo::Sequence protocolDescriptorList;
            QBluetoothServiceInfo::Sequence protocol;
            protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::L2cap))
                     << QVariant::fromValue(port.toUShort());
            protocolDescriptorList.append(QVariant::fromValue(protocol));
            service.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList,
                                 protocolDescriptorList);
            qDebug() << "port" << port.toUShort() << service.protocolServiceMultiplexer();
        }
        else {
            service.setServiceUuid(QBluetoothUuid(serviceUuid));
        }
        service.setDevice(device);
        client->startClient(service);
        board->setStatus("Connecting", 100, 25);
    } else if (nearFieldManager.isAvailable()) {
        board->setStatus(tr("Touch to play"), 100, 25);
    }

    setEnabled(true);

    paddleAnimation = new QPropertyAnimation(this, "paddlePos", this);
    paddleAnimation->setEasingCurve(QEasingCurve::InOutQuad);

    ui->pongView->installEventFilter(this);

}
Ejemplo n.º 16
0
void YapClient::ioCallback(GIOChannel* channel, GIOCondition condition)
{
    if (d == NULL) {
        fprintf(stderr, "YAP: ioCallback was executing on a null YapClientPrv!");
        return;
    }

    if (channel == d->msgServerIoChannel) {
        // Server connected to our message socket. Created a new msg socket for it

        struct sockaddr_un  socketAddr;
        socklen_t           socketAddrLen;

        memset(&socketAddr,    0, sizeof(socketAddr));
        memset(&socketAddrLen, 0, sizeof(socketAddrLen));

        d->msgSocketFd = ::accept(d->msgServerSocketFd, (struct sockaddr*) &socketAddr, &socketAddrLen);

        // Create a new io channel for the receiving messages from the server
        d->msgIoChannel = g_io_channel_unix_new(d->msgSocketFd);
        d->msgIoSource  = g_io_create_watch(d->msgIoChannel, (GIOCondition) (G_IO_IN | G_IO_HUP));

        g_source_set_callback(d->msgIoSource, (GSourceFunc) YapClientPriv::ioCallback, this, NULL);
        g_source_attach(d->msgIoSource, d->mainCtxt);
    }
    else if (channel == d->cmdIoChannel) {
        if (condition & G_IO_HUP) {
            g_message("YAP: Server disconnected command socket");
            closeMsgSocket();
            closeCmdSocket();
            serverDisconnected();
        }
    }
    else if (channel == d->msgIoChannel) {

        char pktHeader[4] = { 0, 0, 0, 0 };
        uint16_t pktLen = 0;
        char * ppp = 0;

        // We either got a message or a server disconnect
        if (condition & G_IO_HUP)
            goto Detached;

        // Get the packet header
        if (!readSocket(d->msgSocketFd, pktHeader, 4)) {
            fprintf(stderr, "YAP: Failed to read packet header\n");
            goto Detached;
        }

        ppp = ((char *)&pktHeader[0]);
        pktLen   = *((uint16_t*) ppp);
        pktLen   = bswap_16(pktLen);

        if (pktLen > kMaxMsgLen) {
            fprintf(stderr, "YAP: ERROR packet length too large: %u > %d\n", pktLen, kMaxMsgLen);
            goto Detached;
        }

        // Get the packet data
        if (!readSocket(d->msgSocketFd, (char*) d->msgBuffer, pktLen)) {
            fprintf(stderr, "YAP: Failed to read packet data of length: %d\n", pktLen);
            goto Detached;
        }

        d->msgPacket->reset();
        d->msgPacket->setReadTotalLength(pktLen);

        handleAsyncMessage(d->msgPacket);

        d->msgPacket->reset();
        d->msgPacket->setReadTotalLength(0);

        return;

    Detached:

        serverDisconnected();
        closeMsgSocket();
        closeCmdSocket();
    }
}
Ejemplo n.º 17
0
Client::Client(QWidget *parent) :
    QDialog(parent), networkSession(0), blockSize(0)
{
    hostLabel = new QLabel(tr("&Server name:"));
    portLabel = new QLabel(tr("S&erver port:"));
    messageLabel = new QLabel(tr("Message:"));
    hostCombo = new QComboBox;
    hostCombo->setEditable(true);


    // find out name of this machine
    QString name = QHostInfo::localHostName();
    if (!name.isEmpty())
    {
        hostCombo->addItem(name);
        QString domain = QHostInfo::localDomainName();
        if (!domain.isEmpty())
            hostCombo->addItem(name + QChar('.') + domain);
    }

    if (name != QString("localhost"))
        hostCombo->addItem(QString("localhost"));

    // find out IP addresses of this machine
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();

    // add non-localhost addresses
    for (int i = 0; i < ipAddressesList.size(); ++i)
    {
        if (!ipAddressesList.at(i).isLoopback())
            hostCombo->addItem(ipAddressesList.at(i).toString());
    }

    // add localhost addresses
    for (int i = 0; i < ipAddressesList.size(); ++i)
    {
        if (ipAddressesList.at(i).isLoopback())
            hostCombo->addItem(ipAddressesList.at(i).toString());
    }

    quitButton = new QPushButton(tr("Quit"));
    sendMessageButton = new QPushButton(tr("Send"));
    sendMessageButton->setEnabled(false);

    connectButton = new QPushButton(tr("Connect"));

    chatBox = new QTextEdit;
    chatBox->setReadOnly(true);

    messageLineEdit = new QLineEdit;
    messageLineEdit->setEnabled(false);

    portLineEdit = new QLineEdit;
    portLineEdit->setValidator(new QIntValidator(1, 65535, this));


    hostLabel->setBuddy(hostCombo);
    portLabel->setBuddy(portLineEdit);

    statusLabel = new QLabel(tr("This examples requires that you run the "
                                    "Fortune Server example as well."));

    tcpSocket = new QTcpSocket(this);

    buttonBox = new QDialogButtonBox;
    buttonBox->addButton(connectButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(sendMessageButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);


    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(hostLabel, 0, 0);
    mainLayout->addWidget(hostCombo, 0, 1);
    mainLayout->addWidget(portLabel, 1, 0);
    mainLayout->addWidget(portLineEdit, 1, 1);
    mainLayout->addWidget(messageLabel, 2, 0);
    mainLayout->addWidget(messageLineEdit, 2, 1);
    mainLayout->addWidget(chatBox, 3, 1);
    mainLayout->addWidget(statusLabel, 4, 0, 1, 2);
    mainLayout->addWidget(buttonBox, 5, 0, 1, 2);
    setLayout(mainLayout);


    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
    connect(sendMessageButton, SIGNAL(clicked()), this, SLOT(sendMessage()));
    connect(connectButton, SIGNAL(clicked()), this, SLOT(connectServer()));
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readingMessage()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));
    connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(serverDisconnected()));
    connect(tcpSocket, SIGNAL(connected()), this, SLOT(disableAddressChange()));
    setWindowTitle("Client");

    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired)
    {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
                QNetworkConfiguration::Discovered)
            config = manager.defaultConfiguration();

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

        connectButton->setEnabled(false);
        statusLabel->setText(tr("Opening network session."));
        networkSession->open();
    }
}
Ejemplo n.º 18
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    _port = new QSpinBox(this);
    _port->setMaximum(99999);
    _port->setValue(8796);
    _host = new QLineEdit(this);
    _host->setFixedWidth(100);
    _connectServer = new QPushButton(tr("Connect"), this);
    _connectServer->setCheckable(true);
    _consult = new QPushButton(tr("Consult"), this);
    _sendCmd  = new QPushButton(tr("Send"), this);
    _cmd  = new QLineEdit(this);
    _serverOutput = new QTextEdit(this);
    _serverOutput->setReadOnly(true);
    _codeEditor = new CodeEditor(this);

    _consult->setEnabled(false);
    _cmd->setEnabled(false);
    _sendCmd->setEnabled(false);

    _client = new Client();

    QObject::connect(_connectServer, SIGNAL(clicked(bool)), this, SLOT(changeServerStatus(bool)));
    QObject::connect(_client, SIGNAL(connected()), this, SLOT(serverConnected()));
    QObject::connect(_client, SIGNAL(disconnected()), this, SLOT(serverDisconnected()));
    QObject::connect(_client, SIGNAL(dataReceived(QString)), this, SLOT(writeServerOutput(QString)));
    QObject::connect(_client, SIGNAL(errorSocket(QString)), this, SLOT(writeServerOutput(QString)));
    QObject::connect(_sendCmd, SIGNAL(clicked()), this, SLOT(sendCmd()));
    QObject::connect(_consult, SIGNAL(clicked()), this, SLOT(consultFile()));

    QHBoxLayout *layoutHeader = new QHBoxLayout;
    layoutHeader->setContentsMargins(10,0,0,10);
    layoutHeader->addWidget(new QLabel(tr("Host"), this));
    layoutHeader->addWidget(_host);
    layoutHeader->addSpacing(10);
    layoutHeader->addWidget(new QLabel(tr("Port"), this));
    layoutHeader->addWidget(_port);
    layoutHeader->addStretch(100);
    layoutHeader->addWidget(_connectServer);

    QSplitter *centralSplitter = new QSplitter(this);
    centralSplitter->addWidget(_codeEditor);
    centralSplitter->addWidget(_serverOutput);

    QHBoxLayout *layoutBottom = new QHBoxLayout;
    layoutBottom->addWidget(_consult, 1);
    layoutBottom->addWidget(_cmd, 100);
    layoutBottom->addWidget(_sendCmd, 1);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setMargin(0);
    mainLayout->setSpacing(0);
    mainLayout->addLayout(layoutHeader, 1);
    mainLayout->addWidget(centralSplitter);
    mainLayout->addLayout(layoutBottom, 1);

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(mainLayout);

    this->setCentralWidget(centralWidget);
}