服务器
头文件
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QLine>
#include <QTcpServer>
#include <QTcpSocket>
#include <QMessageBox>QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_startbtn_clicked();void newConnection_slot();void readyRead_slot();
private:Ui::Widget *ui;//服务器指针QTcpServer *server;//客户端容器QList<QTcpSocket *> clientlist;};
#endif // WIDGET_H
主函数
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QLine>
#include <QTcpServer>
#include <QTcpSocket>
#include <QMessageBox>QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_startbtn_clicked();void newConnection_slot();void readyRead_slot();
private:Ui::Widget *ui;//服务器指针QTcpServer *server;//客户端容器QList<QTcpSocket *> clientlist;};
#endif // WIDGET_H
客户端
头文件
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTcpSocket>
#include <QMessageBox>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_sendBtn_clicked();void on_connectBtn_clicked();void on_disconnectBtn_clicked();void disconnectBtn_slot();void connected_slot();void readyRead_slot();
private:Ui::Widget *ui;QTcpSocket *socket;QString name;
};
#endif // WIDGET_H
主函数
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);//实例化一个客户端socket= new QTcpSocket(this);//连接connect(socket,&QTcpSocket::connected,this,&Widget::connected_slot);//读取connect(socket,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);//断开connect(socket,&QTcpSocket::disconnected,this,&Widget::disconnectBtn_slot);
}Widget::~Widget()
{delete ui;
}void Widget::on_sendBtn_clicked()
{//组合数据QString msg =name+":"+ui->lineEdit->text();//发送socket->write(msg.toLocal8Bit());//清空ui->lineEdit->clear();
}void Widget::on_connectBtn_clicked()
{//用户名name=ui->userNameEdit->text();//主机地址QString ip=ui->ipEdit->text();//端口号quint16 port=ui->portEdit->text().toUInt();socket->connectToHost(ip,port);
}void Widget::on_disconnectBtn_clicked()
{QString msg=name+":离开聊天室";socket->write(msg.toLocal8Bit());//发送断开信号socket->disconnectFromHost();
}void Widget::disconnectBtn_slot()
{QMessageBox::information(this,"提示","推出成功");
}
void Widget::connected_slot()
{QMessageBox::information(this,"成功","您已经成功进入聊天室");QString msg=name+":进入聊天室";socket->write(msg.toLocal8Bit());
}
void Widget::readyRead_slot()
{QByteArray msg =socket->readAll();ui->msgWid->addItem(QString::fromLocal8Bit(msg));
}
现象