当前位置: 代码迷 >> QT开发 >> 用QTcpSocket作客户端用来测试TCP,但不能接收数据,求指教
  详细解决方案

用QTcpSocket作客户端用来测试TCP,但不能接收数据,求指教

热度:90   发布时间:2016-04-25 04:18:17.0
用QTcpSocket做客户端用来测试TCP,但不能接收数据,求指教!
#include <QMessageBox>
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setFixedSize( this->width (),this->height ()); //固定窗口大小
    TcpSocket = new QTcpSocket(this);
    connect(ui->ConnectBtn,SIGNAL(clicked()),this,SLOT(Connect()));
    connect(ui->StopBtn,SIGNAL(clicked()),this,SLOT(Stop()));
    connect(ui->ClearReceiveBtn,SIGNAL(clicked()),this,SLOT(ClearReceive()));
    connect(ui->ClearSendBtn,SIGNAL(clicked()),this,SLOT(ClearSend()));
    connect(ui->SendBtn,SIGNAL(clicked()),this,SLOT(Send()));
    connect(TcpSocket,SIGNAL(readyRead()),this,SLOT(ReadMessage()));
    connect(TcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),
             this,SLOT(displayError(QAbstractSocket::SocketError)));
}

Widget::~Widget()
{
    delete ui;
}


void Widget::displayError(QAbstractSocket::SocketError)
{
    qDebug() << TcpSocket->errorString(); //输出错误信息
}

void Widget::ReadMessage()
{
    qDebug("Read");
    if(TcpSocket->waitForConnected(30000)){
    QString Msg;
    QByteArray qba = TcpSocket->readAll();
    Msg=QVariant(qba).toString();
    ui->Receive_textBrowser->append(Msg);}
}

void Widget::Connect()
{
  //  BlockSize = 0; //初始化其为0
    TcpSocket->abort(); //取消已有的连接
    TcpSocket->connectToHost(ui->Remote_IP_lineEdit->text(),
                               ui->Remote_Port_lineEdit->text().toInt());
    ui->ConnectBtn->setEnabled(false);
    ui->StopBtn->setEnabled(true);
}

void Widget::Stop()
{
    TcpSocket->close();
    qDebug("socket break");
    ui->StopBtn->setEnabled(false);
    ui->ConnectBtn->setEnabled(true);
}

void Widget::Send()
{
    qDebug("send message");
    int length = 0;
    QString Msg= ui->SendMsg_lineEdit->text();
    if((length = TcpSocket->write(Msg.toStdString().c_str(),strlen(Msg.toStdString().c_str()))) != Msg.length())
    {
        qDebug("send fail");
    }
    qDebug("%d", length);
    qDebug()<< Msg;
}

void Widget::ClearSend()
{
    ui->SendMsg_lineEdit->setText ("");
}

void Widget::ClearReceive()
{
    ui->Receive_textBrowser->setText("");
}


------最佳解决方案--------------------