我们在上篇中,服务器收到的消息是由线程类去处理的,消息在线程类中,传不到widget中的ui中去,如果我们要在界面显示客户端的消息,必须通过自定义信号.
1.构建信号
当线程收到信息,就会被填充在ba中,然后sendtowidget函数在接收到ba参数的时候就会发出信号给widget,为什么会发送信号给widget,我们可以在widget中写一个connect联系起来,如下图
2.演示
自定义信号
3.代码实现
qtthread.h
#ifndef QTTHREAD_H
#define QTTHREAD_H
#include <QObject>
#include<QThread>
#include<QTcpSocket>
#include<QDebug>
class qtthread : public QObject
{
Q_OBJECT
public:
explicit qtthread(QTcpSocket*s,QObject *parent = nullptr);
void run();
void serverrecv();
signals:
void sendtowidget(QByteArray t);
private:
QTcpSocket* s;
};
#endif // QTTHREAD_H
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QTcpSocket>
#include<QTcpServer>
#include<qtthread.h>
//#include<QThread>
#define PORT 8080
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void deal();
// void serverrecv();
void threaddeal(QByteArray st);
private:
Ui::Widget *ui;
QTcpServer *server;
};
#endif // WIDGET_H
qtthread.cpp
#include "qtthread.h"
qtthread::qtthread(QTcpSocket *socket, QObject *parent) : QObject(parent)
{
s=socket;
}
void qtthread :: run()
{
connect(s,&QTcpSocket::readyRead,this,&qtthread::serverrecv);
}
void qtthread ::serverrecv()
{
// qDebug()<<s->readAll();
QByteArray ba=s->readAll();
emit sendtowidget(ba);
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
server=new QTcpServer;
server->listen(QHostAddress::AnyIPv4,PORT);
connect(server,&QTcpServer::newConnection,this,&Widget::deal);
}
Widget::~Widget()
{
delete ui;
}
void Widget::deal()
{
QTcpSocket* socket=server->nextPendingConnection();
ui->clientip->setText(socket->peerAddress().toString());
ui->clientport->setText(QString::number(socket->peerPort()));
// connect(socket,&QTcpSocket::readyRead,this,&Widget::serverrecv);
qtthread *st=new qtthread(socket);
st->run();
connect(st,&qtthread::sendtowidget,this,&Widget::threaddeal);
}
//void Widget::serverrecv()
//{
// QTcpSocket* socket=(QTcpSocket*)sender();
// // socket->readAll();//QBytearray
// ui->recvinfo->setText(QString(socket->readAll()));
//}
void Widget::threaddeal(QByteArray st)
{
ui->recvinfo->setText(QString(st));
}