QT开发的即时通讯软件(基于TCP)

这是本人在学习QT和计算机网络的时候自己开发的TCP网络通讯软件,包含服务端和客户端两个工程,亲测可用,我自己也经常用它们做网络的测试,注释详细,欢迎参考,先上图,源码附在下面,也可以直接在这下载:https://download.csdn.net/download/qq_18108083/10798425  赚点积分,嘿嘿,谢谢大家~

一、server端

(1).mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpServer>
#include <QTextCodec>//保证正常显示中文
#include <QTcpSocket>
#include <QDebug>
#include <QMessageBox>
#include <QByteArray>
#include <QImage>  //图片
#include <QTimer>
#include <QBuffer>
#include <mythread.h>  //线程实验
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    QImage *image;
    QTimer *timer;

    //线程实验
    myThread *thread;
    int pb;
private:
    Ui::MainWindow *ui;
    QTcpServer *tserver;
    QTcpSocket *tsocket;

private slots:
    void listenStartSlot();  //开始侦听槽
    void newConnectSlot();   //收到新连接
    void receiveTcpSlot();   //槽函数用于对接受的数据进行处理
    void sendTcpSlot();      //发送tcp信号槽(发送按钮触发)
    void tcpDisconnect();    //tcp连接中断

    //线程实验
    void closeThreadSlot();
};

#endif // MAINWINDOW_H

(2).mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    tserver =new QTcpServer;  //创建新TCP服务器

    QObject::connect(ui->listenButton,SIGNAL(clicked(bool)),this,SLOT(listenStartSlot()));  //开始侦听
    QObject::connect(this->tserver,SIGNAL(newConnection()),this,SLOT(newConnectSlot()));  //侦听到新连接
    QObject::connect(ui->sendButton,SIGNAL(clicked(bool)),this,SLOT(sendTcpSlot()));  //发送数据

    //线程实验
    QObject::connect(ui->closeThreadButton,SIGNAL(clicked(bool)),this,SLOT(closeThreadSlot()));
    //线程实验
    pb=0;
    thread=new myThread(pb);
    thread->start();
}

MainWindow::~MainWindow()
{
    tserver->close();
    tserver->deleteLater();

    delete thread;  //线程实验
    delete ui;
}
void MainWindow::listenStartSlot()  //开始侦听槽
{
    if(ui->listenButton->text()=="侦听")
    {
        quint16 port=quint16(ui->listenPortLineEdit->text().toUInt());//获取监听端口
        qDebug()<<"port:"<<port;
        if(!tserver->listen(QHostAddress::Any,port))
        {
            QMessageBox::information(this,"提示","侦听设置出错");
            return;
        }
        else
        {
            QMessageBox::information(this,"提示","开始侦听");
            ui->listenButton->setText("取消侦听");
        }

    }
    else
    {
        if(tsocket->state()==QAbstractSocket::ConnectedState)
        {
            tsocket->disconnectFromHost();  //关闭连接

        }
        tserver->close();  //取消侦听
        ui->listenButton->setText("侦听");
    }

}

void MainWindow::newConnectSlot()   //收到新连接
{
    tsocket=tserver->nextPendingConnection();  //server让自己的socket与client的socket相连
    QObject::connect(this->tsocket,SIGNAL(disconnected()),this,SLOT(tcpDisconnect()));  //套接字断开连接
    QObject::connect(this->tsocket,SIGNAL(readyRead()),this,SLOT(receiveTcpSlot()));  //收到数据
    QMessageBox::information(this,"提示","侦听到新连接");

}

void MainWindow::receiveTcpSlot()   //槽函数用于对接受的数据进行处理
{
    QByteArray receiveData; //因为传来的数据类型是未知的,用bytearray类型
    receiveData=tsocket->readAll();
    ui->receiveContextTextEdit->append(QString::fromUtf8(receiveData));   //

}
void MainWindow::sendTcpSlot()      //发送tcp信号槽(发送按钮触发)
{

    //发送图片
  //      qDebug()<<"sendPicture clicked"<<endl;

   //     QPixmap pixmap(tr("th.jpg"));
   //     QBuffer buffer;
   //    buffer.open(QIODevice::ReadWrite);
   //     pixmap.save(&buffer,"jpg");
   //     quint32 pixmap_len = (quint32)buffer.data().size();
   //     qDebug("image size:%d",pixmap_len);

  //      QByteArray dataArray;
   //     dataArray.append(buffer.data());

    //    quint32 write_len = tsocket->write(dataArray);
   //     qDebug("write len:%d",write_len);


    //添加判断连接
    QString sendContext=ui->sendContextTextEdit->document()->toPlainText();//
    tsocket->write(sendContext.toUtf8());  //以Utf8形式的bytearray发送
    tsocket->flush();

}
void MainWindow::tcpDisconnect()    //tcp连接中断
{
    ui->listenButton->setText("侦听");
    QMessageBox::information(this,"提示","TCP连接中断");

}
void MainWindow::closeThreadSlot()
{
    delete thread;

}

二、client端

(1).mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTextCodec>//保证正常显示中文
#include <QTcpSocket>
#include <QDebug>
#include <QMessageBox>
#include <QByteArray>
#include <QIODevice>
#include <QBuffer>
#include <QImageReader>
#include <QDataStream>    //数据流
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QTcpSocket *tsocket;

private slots:
    void connectHostSlot();  //请求建立连接
    void receiveTcpSlot();   //槽函数用于对接受的数据进行处理

    void sendTcpSlot();      //发送tcp信号槽(发送按钮触发)
    void tcpDisconnect();    //tcp连接中断
};

#endif // MAINWINDOW_H

(2)mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{


    ui->setupUi(this);

    tsocket =new QTcpSocket;  //新建一个TCP套接字


    QObject::connect(ui->connectButton,SIGNAL(clicked(bool)),this,SLOT(connectHostSlot()));  //连接主机
    QObject::connect(ui->sendButton,SIGNAL(clicked(bool)),this,SLOT(sendTcpSlot()));  //发送数据
    QObject::connect(tsocket,SIGNAL(readyRead()),this,SLOT(receiveTcpSlot()));  //接收数据
    QObject::connect(tsocket,SIGNAL(disconnected()),this,SLOT(tcpDisconnect()));  //tcp连接中断

}

MainWindow::~MainWindow()
{
    delete ui;
    delete this->tsocket;  //清理内存
}
void MainWindow::connectHostSlot()  //请求建立连接
{
    if(ui->connectButton->text()=="连接")
    {
        QString hostip=ui->hostIpLineEdit->text();  //获取主机ip
        quint16 hostport=quint16(ui->hostPortLineEdit->text().toUInt());  //获取主机端口
        tsocket->abort(); //取消已有连接
        tsocket->connectToHost(hostip,hostport);  //请求与服务器建立连接

        if(!tsocket->waitForConnected(30000))  //等待30s
        {
            QMessageBox::information(this,"提示","连接失败");
            return;
        }
        else
        {
            QMessageBox::information(this,"提示","连接成功");

            ui->connectButton->setText("断开连接");
        }
    }
    else
    {
        tsocket->disconnectFromHost();  //断开连接
        ui->connectButton->setText("连接");
    }
}
void MainWindow::receiveTcpSlot()   //槽函数用于对接受的数据进行处理
{



//         QByteArray array;
//         while(tsocket->waitForReadyRead(1)){           //连续接收 ,知道接收完毕
//             qDebug()<<"bytesAvailable"<<endl;
//             array.append((QByteArray)tsocket->readAll());
//         }
//
//         QBuffer buffer(&array);
//         buffer.open(QIODevice::ReadOnly);
//
//         QImageReader reader(&buffer,"JPG");
//         QImage img = reader.read();
//
//         if(!img.isNull()){
//             qDebug()<<"right"<<endl;
//             ui->imageLabel->setPixmap(QPixmap::fromImage(img).scaled(ui->imageLabel->size()));//按比例缩放
//         } else {
//             qDebug()<<"error"<<endl;
//         }

    QByteArray receiveData; //因为传来的数据类型是未知的,用bytearray类型
    receiveData=tsocket->readAll();
    ui->receiveContextTextEdit->append(QString::fromUtf8(receiveData));   //转换成char *

}
void MainWindow::sendTcpSlot()      //发送tcp信号槽(发送按钮触发)
{
    //添加判断连接
    QString sendContext=ui->sendContextTextEdit->document()->toPlainText();//
//    tsocket->write(sendContext.toLatin1());
    tsocket->write(sendContext.toUtf8());  //将QString转换成QByteArray类型发送
    tsocket->flush();
}
void MainWindow::tcpDisconnect()    //tcp连接中断
{
    ui->connectButton->setText("连接");
    QMessageBox::information(this,"提示","TCP连接中断");
}

 

  • 8
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值