qt TCP socket通信实例——网络聊天室
说明:
数据的传输使用json,实现了一些基本的聊天功能,服务端的禁言功能,在线用户的显示功能,我会把源码放在下面,但是要提前说明的是这个网络聊天室有一些很迷惑的bug,而以本人目前的能力没有办法修复,所以请想要直接抄代码的同学谨慎一点
演示:

上面的ip是我的内网ip,其实填172.0.0.1就可以在任意的测试机器上达到图片上的效果
代码如下
服务端:
//mainwindown.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<QTcpServer>
#include<QTcpSocket>
#include<QHostAddress>
#include<QDateTime>
#include<QString>
#include<QColor>
#include<QFontDialog>
#include<QLabel>
#include<QPoint>
#include<QFont>//想要实现字体和颜色的传输,但是后来放弃了
#include<QColorDialog>
#include<QFontDialog>
#include<QPushButton>
#include<QJsonValue>
#include<QJsonObject>
#include<QJsonDocument>
#include<QListWidget>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
QList<QTcpSocket * > socketlist;
QString name;
QString message;
QLabel * status;
QLabel * perm;
QTcpServer * server;
void decode(const QByteArray &);
void showmessage(const QString & str);
void ini();
bool speakable;
int count;
QByteArray encode(const QString & name,const QString & message);
~MainWindow();
private slots:
void on_actionopen_triggered();
void slo_newconnnection();
void slo_disconnection();
void slo_revmess();
void on_sendButton_clicked();
void on_actionclose_triggered();
void on_clearbutton_clicked();
void on_toolButton_clicked();
void on_toolButton_2_clicked();
void on_toolButton_3_clicked();
void on_toolButton_4_clicked();
void on_actionforbid_triggered();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<qdebug.h>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ini();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::ini()
{
status=new QLabel(QString::fromUtf8("欢迎"));
perm= new QLabel(QString::fromUtf8("网络聊天室"));
ui->statusBar->addWidget(status);
ui->statusBar->addPermanentWidget(perm);
ui->actionclose->setEnabled(false);
ui->mess_rec->setReadOnly(true);
speakable=true;
count=0;
ui->iplist->setRowCount(0);
}
void MainWindow::on_actionopen_triggered()
{
ui->actionopen->setEnabled(false);
ui->actionclose->setEnabled(true);
server=new QTcpServer;
server->listen(QHostAddress(ui->ipline->text()),ui->portline->text().toShort());
connect(server,&QTcpServer::newConnection,this,&MainWindow::slo_newconnnection);
}
void MainWindow::showmessage(const QString & str)
{
QDateTime time=QDateTime::currentDateTime();
ui->mess_rec->append(time.toString("MM-dd hh:mm:ss")+" "+str);
}
void MainWindow::slo_newconnnection()
{
QTcpSocket * socket=server->nextPendingConnection();
connect(socket,&QTcpSocket::readyRead,this,&MainWindow::slo_revmess);