티스토리 뷰

반응형

QTcpSocket 클래스를 사용하려면 .pro 파일에 QT += network 등록하여야 합니다.

 

// mytcpsocket.h

#include <QObject>

#include <QTcpSocket>

#include <QAbstractSocket>

#include <QDebug>

 

class MyTcpSocket : public QObject

{

    Q_OBJECT

public:

    explicit MyTcpSocket(QObject *parent = 0);

    

    void doConnect();

 

signals:

    

public slots:

    void connected();

    void disconnected();

    void bytesWritten(qint64 bytes);

    void readyRead();

 

private:

    QTcpSocket *socket;

    

};

 

 

// mytcpsocket.cpp

#include "mytcpsocket.h"

 

MyTcpSocket::MyTcpSocket(QObject *parent) : QObject(parent)

{

}

 

void MyTcpSocket::doConnect()

{

    socket = new QTcpSocket(this);

 

    connect(socket, SIGNAL(connected()),this, SLOT(connected()));

    connect(socket, SIGNAL(disconnected()),this, SLOT(disconnected()));

    connect(socket, SIGNAL(bytesWritten(qint64)),this, SLOT(bytesWritten(qint64)));

    connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()));

 

    qDebug() << "connecting...";

 

    // this is not blocking call

    socket->connectToHost("google.com", 80);

 

    // we need to wait...

    if(!socket->waitForConnected(5000))

    {

        qDebug() << "Error: " << socket->errorString();

    }

}

 

void MyTcpSocket::connected()

{

    qDebug() << "connected...";

 

    // Hey server, tell me about you.

    socket->write("HEAD / HTTP/1.0\r\n\r\n\r\n\r\n");

}

 

void MyTcpSocket::disconnected()

{

    qDebug() << "disconnected...";

}

 

void MyTcpSocket::bytesWritten(qint64 bytes)

{

    qDebug() << bytes << " bytes written...";

}

 

void MyTcpSocket::readyRead()

{

    qDebug() << "reading...";

 

    // read the data from the socket

    qDebug() << socket->readAll();

}

 

반응형

'프로그래밍 > Qt' 카테고리의 다른 글

QTimer  (0) 2019.06.11
Qt5 배포 후 한글 안될 때  (0) 2019.06.11
Thread 이벤트 Gui 폼에서 받기  (0) 2019.06.11
QMutex (쓰레드 동기화)  (0) 2019.06.11
Thrad 실행 우선순위  (0) 2019.06.11
댓글
반응형
최근에 올라온 글
Total
Today
Yesterday