请问如何做一个tcp客户端访问网页
本帖最后由 oXiFangShiBai 于 2013-02-01 10:28:15 编辑
使用tcp协议,来访问网页,这样主要是做一个长连接
我的实现思路是:
1.连接 服务器 【举例用百度 www.baidu.com】
2.发送http协议头,获取服务器返回网页内容 并 处于监控状态,因为服务器会每隔1分钟发心跳包给我,我的目的就是要得到心跳包的内容,
3.我的代码如下,出现的问题是,发送了http协议头,服务器没有任何反映,我用wireshark抓包,甚至没有变成http请求,我想,一定是我发送的时候出了问题,但自己研究了半天没弄好,所以来请教大家
下面贴上我的代码
client.h
//client.h
#ifndef TRYCLI_H_
#define TRYCLI_H_
#include
#include
#include
#include
#include
#include
#include
class Client : public QWidget
{
Q_OBJECT
private:
bool isConnected;
QLineEdit *serverIpEdit;
QLabel *label;
QPushButton *startButton;
QTcpSocket *tcpClient;
quint16 blockSize;
QString sendString;
QString readString;
public:
Client();
~Client();
public slots:
void displayError(QAbstractSocket::SocketError socketError);
void newConnect();
void readMessage();
void sendMessage();
};
#endif
//client.cpp
//client.cpp
#include "client.h"
#include
#include
#include
#include
#include
#include
Client::Client()
{
setWindowTitle("Client");
resize(300, 100);
serverIpEdit = new QLineEdit("www.baidu.com");
startButton = new QPushButton("start");
label = new QLabel("Emtpy");
isConnected = false;
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(serverIpEdit);
layout->addWidget(label);
layout->addWidget(startButton);
setLayout(layout);
tcpClient = new QTcpSocket(this);
connect(startButton, SIGNAL(clicked()), this, SLOT(newConnect()));
connect(tcpClient, SIGNAL(connected()), this, SLOT(sendMessage()));
connect(tcpClient, SIGNAL(readyRead()), this, SLOT(readMessage()));
connect(tcpClient, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(displayError(QAbstractSocket::SocketError)));
}
Client::~Client()
{
}
void Client::newConnect()
{
blockSize = 0;
tcpClient->abort();
tcpClient->connectToHost(serverIpEdit->text(), 80);