Qt---QTcpSocket连接http服务器

Qt---QTcpSocket连接http服务器_第1张图片

tcp.pro

#-------------------------------------------------
#
# Project created by QtCreator 2016-06-29T20:24:24
#
#-------------------------------------------------

QT       += core network
QT       -= core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = tcp
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app


SOURCES += main.cpp\
    client.cpp

HEADERS  += \
    client.h

client.h

#ifndef CLIENT_H
#define CLIENT_H
#include 

class Client: public QObject
{
    Q_OBJECT
 public:
    Client(): m_socket(0){}
    ~Client(){}
    void startConnect(QString host, quint16 prot);  //连接主机

 protected slots:
    void onConnected(); //发送
    void onReadyRead();  //读取

 private:
    QTcpSocket *m_socket;
};

#endif

client.cpp

#include "client.h"
#include 

void Client::startConnect(QString host, quint16 port)
{
    m_socket = new QTcpSocket(this);
    connect(m_socket, SIGNAL(connected()), this, SLOT(onConnected()));
    connect(m_socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    m_socket->connectToHost(host, port);  //连接主机
}

void Client::onConnected()
{
    m_socket->write("GET / HTTP/1.1\r\n\r\n");  //向服务器端发送数据,http头部
}

void Client::onReadyRead()  //接收数据
{
    qDebug() << m_socket->readAll();  //打印出来
}

main.cpp

#include "mainwindow.h"
#include "client.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Client client;
    client.startConnect("www.baidu.com", 80);

    return a.exec();
}

Qt---QTcpSocket连接http服务器_第2张图片

你可能感兴趣的:(Qt)