目录
一·、服务器端实现
代码:
chatserver.h
#ifndef CHATSERVER_H
#define CHATSERVER_H
#include <QWidget>
#include<QTcpServer>
#include<QTcpSocket>
#include<QList>
QT_BEGIN_NAMESPACE
namespace Ui { class ChatServer; }
QT_END_NAMESPACE
class ChatServer : public QWidget
{
Q_OBJECT
public:
ChatServer(QWidget *parent = nullptr);
~ChatServer();
private slots:
void on_startBtn_clicked();
void on_newConnection_slot();
void on_readyRead_slot();
void send(QString mes); //自定义广播函数
private:
Ui::ChatServer *ui;
//定义服务器指针
QTcpServer *server;
//定义客户端指针
QList<QTcpSocket *> socketList;
};
#endif // CHATSERVER_H
chatserver.cpp
#include "chatserver.h"
#include "ui_chatserver.h"
#include<QMessageBox>
ChatServer::ChatServer(QWidget *parent)
: QWidget(parent)
, ui(new Ui::ChatServer)
{
ui->setupUi(this);
//实例化服务器
server = new QTcpServer(this);
}
ChatServer::~ChatServer()
{
delete ui;
}
//启动按钮对应的槽函数
void ChatServer::on_startBtn_clicked()
{
quint16 port = quint16(ui->portEdit->text().toInt());
//将服务器设置为监听状态
server->listen(QHostAddress::Any,port);
//将相应的控件设置为不可用状态
ui->portEdit->setEnabled(false);
ui->sta