您的位置:首页 > 编程语言 > Qt开发

Qt---QTcpSocket连接http服务器

2016-06-29 20:55 344 查看


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 <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();
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: