Qt---QTcpSocket连接http服务器

来源:互联网 发布:什么软件字体多 编辑:程序博客网 时间:2024/05/29 15:03

这里写图片描述

tcp.pro

#-------------------------------------------------## Project created by QtCreator 2016-06-29T20:24:24##-------------------------------------------------QT       += core networkQT       -= core guigreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = tcpCONFIG += consoleCONFIG -= app_bundleTEMPLATE = appSOURCES += main.cpp\    client.cppHEADERS  += \    client.h

client.h

#ifndef CLIENT_H#define CLIENT_H#include <QTcpSocket>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 <QDebug>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 <QApplication>int main(int argc, char *argv[]){    QApplication a(argc, argv);    Client client;    client.startConnect("www.baidu.com", 80);    return a.exec();}

这里写图片描述

0 0
原创粉丝点击