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

ccp668 ccp668 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
#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("");
}

...全文

相关推荐

评论 24
收藏 已收藏
分享
返回顶部
ccp668
Qt 21,503 成员 26,693 内容