Qt/Classes

QTcpSocket Class Examples

아침엔커피한잔 2017. 7. 16. 14:22

http://doc.qt.io/qt-5/qtcpsocket.html


    
// client
QTcpSocket *tcpSocket;
QDataStream in;
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    tcpSocket(new QTcpSocket(this))
...
connect(tcpSocket, &QIODevice::readyRead, this, &MainWindow::readClient);
 typedef void (QAbstractSocket::*QAbstractSocketErrorSignal)(QAbstractSocket::SocketError);
 connect(tcpSocket, static_cast(&QAbstractSocket::error), this, &MainWindow::displayError);
...
// connect
tcpSocket->abort();
tcpSocket->connectToHost(ui->hostComboBox->currentText(),15001);
...
void MainWindow::readClient()
{
in.startTransaction();
QString clientData;
in >> clientData;
if(!in.commitTransaction()) return;
...
void MainWindow::displayError(QAbstractSocket::SocketError socketError)
{
    switch (socketError) {
    case QAbstractSocket::RemoteHostClosedError:
        break;
    case QAbstractSocket::HostNotFoundError:
        QMessageBox::information(this, tr("Fortune Client"),
                                 tr("The host was not found. Please check the "
                                    "host name and port settings."));
        break;
    case QAbstractSocket::ConnectionRefusedError:
        QMessageBox::information(this, tr("Fortune Client"),
                                 tr("The connection was refused by the peer. "
                                    "Make sure the fortune server is running, "
                                    "and check that the host name and port "
                                    "settings are correct."));
        break;
    default:
        QMessageBox::information(this, tr("Fortune Client"),
                                 tr("The following error occurred: %1.")
                                 .arg(tcpSocket->errorString()));
    }

 //   getFortuneButton->setEnabled(true);
}

//server
if(!server.listen(QHostAddress::Any, 15001)){
        QMessageBox::critical(this,tr("Threaded Server"), tr("Unable to start the server: %1.").
                              arg(server.errorString()));
        return;
}
void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{
    MyThread *thread = new MyThread(socketDescriptor, this);
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    thread->start();
}

int MyThread::no = 0;
MyThread::MyThread(int socketDescriptor, QObject *parent)
    : QThread(parent), socketDescriptor(socketDescriptor)
{
    no++;
    return;
}
MyThread::~MyThread()
{
    no--;
    return;
}

void MyThread::run()
{
    qDebug() << "MyThread run " << no;

    QTcpSocket tcpSocket;

    if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
        emit error(tcpSocket.error());
        return;
    }


    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out <<  tr("You might have mail.");


    tcpSocket.write(block);
    tcpSocket.disconnectFromHost();
    tcpSocket.waitForDisconnected();
}
-


   
//client
...
void MainWindow::readClient()
{
    qDebug() << "MainWindow::readClient";
//    in.startTransaction();

//    QString clientData;
//    in >> clientData;

//    if(!in.commitTransaction()) return;
    QByteArray clientData = tcpSocket->readAll();
    qDebug() << "recv : " << clientData;
...
//server
...
    server.StartServer();
...
int MyRunnable::no = 0;
MyRunnable::MyRunnable()
{
    no++;
    qDebug() << "task create " << no;
}
MyRunnable::~MyRunnable()
{
    no--;
    qDebug() << "task deleted " << no;
}

void MyRunnable::run()
{
    qDebug() << "MyRunnable::run";
  if (!socketDescriptor)
    return;

  QTcpSocket socket;
  socket.setSocketDescriptor(socketDescriptor);
  QByteArray data("");
  data.append(QObject::tr("hello world"));
  socket.write(QObject::tr("hello world").toUtf8());
  socket.flush();
  socket.waitForBytesWritten();
  socket.close();
}

MyServer::MyServer(QObject *parent):
  QTcpServer(parent)
{
  //Create a threadpool
  pool = new QThreadPool(this);

  //How many threads I want at any given time
  //If there are more connections, they will be qued until a threads is closed
  pool->setMaxThreadCount(5);   // ex. 5 threads
}


void MyServer::StartServer()
{
  if (!this->listen(QHostAddress::Any, 15001))
  {
//    QMessageBox::critical(this, tr("Server"),
//                                          tr("Unable to start the server: %1.")
//                                          .arg(this->errorString()));
    qDebug() << "Unable to start server - " << this->errorString();
  }
  else
  {
      qDebug() << "MyServer::startServer : listening";
    //Server is now listening..
  }
}

void MyServer::incomingConnection(qintptr socketDescriptor)
{
    qDebug() << "MyServer::incomingConnection " << socketDescriptor;
  MyRunnable *task = new MyRunnable();
  //task->setAutoDelete(true);                        //Delete that object when you're done (instead of using signals and slots)

  task->socketDescriptor = socketDescriptor;

  //pool->start(task);                               //Uses a QRunnable object
  QThreadPool::globalInstance()->start(task);

    // QThreadPool takes ownership and deletes 'hello' automatically
//    HelloWorldTask *hello = new HelloWorldTask();
//    QThreadPool::globalInstance()->start(hello);
}
-