Qt: 基于QTcpSocket的聊天程序

2023-10-08 17:58
文章标签 程序 qt 聊天 qtcpsocket

本文主要是介绍Qt: 基于QTcpSocket的聊天程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

下载地址:http://download.csdn.net/detail/rl529014/9660330          C++、Qt学习交流群: 302558294(欢迎你的加入)

效果图:



原理:

用到的库:QTcpServer,QTcpServer,QHostAddress,QtNetwork。


源码:

服务器端:

//mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QtNetwork>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
#include <QByteArray>namespace Ui
{
class MainWindow;
}class MainWindow : public QMainWindow
{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = 0);~MainWindow();public:void init();private slots:void sendMessage(); //发送消息void onReciveData();  //接收数据void newListen(); //建立tcp监听事件void acceptConnection(); //接收客户端连接void showError(QAbstractSocket::SocketError); //错误输出private:Ui::MainWindow *ui;private:QTcpSocket *tcpSocket;QTcpServer *tcpServer;// QTimer *timer;QByteArray mChat;
};#endif // MAINWINDOW_H

//mainwindow.cpp

#include <QObject>
#include <QString>
#include <QTextEdit>
#include <QHostAddress>
#include <QByteArray>
#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),ui(new Ui::MainWindow)
{ui->setupUi(this);init();setWindowTitle(QString::fromLocal8Bit("服务器端"));connect(ui->sendBtn,SIGNAL(clicked(bool)),SLOT(sendMessage()));
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::init()
{// timer = new QTimer;tcpServer = new QTcpServer;tcpSocket = new QTcpSocket;newListen();connect(tcpServer,SIGNAL(newConnection()),SLOT(acceptConnection()));connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),SLOT(showError(QAbstractSocket::SocketError)));}void MainWindow::sendMessage()  //发送数据
{QString textEdit = ui->lineEdit->text();QString strData =QString::fromLocal8Bit("Time: ") + QTime::currentTime().toString() + "\n" + textEdit.toLocal8Bit() + "\n";QByteArray sendMessage = strData.toLocal8Bit();mChat += ("Send " + sendMessage);ui->textEdit->setText(mChat);tcpSocket->write(sendMessage);
}void MainWindow::onReciveData()  //读取数据
{QString data = tcpSocket->readAll();qDebug()<<data;mChat +=("Recv " + data);ui->textEdit->setText(mChat);
}void MainWindow::newListen()
{if(!tcpServer->listen(QHostAddress::Any,6666)){qDebug()<<tcpServer->errorString();tcpServer->close();}
}void MainWindow::acceptConnection()
{tcpSocket = tcpServer->nextPendingConnection();connect(tcpSocket,SIGNAL(readyRead()),SLOT(onReciveData()));
}void MainWindow::showError(QAbstractSocket::SocketError)
{qDebug()<<tcpSocket->errorString();tcpSocket->close();
}


客户端:

//mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QtNetwork>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
#include <QAbstractSocket>
namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = 0);~MainWindow();public:void init();void newTcpConnect();private slots:void onReciveData();void onSendMessage();void onShowError(QAbstractSocket::SocketError);private:QTcpSocket *tcpSocket;QByteArray mChat;private:Ui::MainWindow *ui;
};#endif // MAINWINDOW_H


//mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{ui->setupUi(this);setWindowTitle(QString::fromLocal8Bit("客户端"));init();connect(ui->sendBtn,SIGNAL(clicked(bool)),SLOT(onSendMessage()));
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::init()
{tcpSocket = new QTcpSocket;newTcpConnect();connect(tcpSocket,SIGNAL(readyRead()),SLOT(onReciveData()));
}void MainWindow::newTcpConnect()
{tcpSocket->abort();tcpSocket->connectToHost("127.0.0.1",6666);
}void MainWindow::onReciveData()
{QString data = tcpSocket->readAll();qDebug()<<data;mChat += ("Recv " + data);ui->textEdit->setText(mChat);
}void MainWindow::onSendMessage()
{QString textEdit = ui->lineEdit->text();QString strData =QString::fromLocal8Bit("Time: ") + QTime::currentTime().toString() + "\n" + textEdit.toLocal8Bit() +"\n";QByteArray sendMessage = strData.toLocal8Bit();mChat+= ("Send " + sendMessage);ui->textEdit->setText(mChat);tcpSocket->write(sendMessage);
}void MainWindow::onShowError(QAbstractSocket::SocketError)
{qDebug()<<tcpSocket->errorString();tcpSocket->close();
}


下载地址:http://download.csdn.net/detail/rl529014/9660330


C++、Qt学习交流群: 302558294(欢迎你的加入)

这篇关于Qt: 基于QTcpSocket的聊天程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/167015

相关文章

Python程序的文件头部声明小结

《Python程序的文件头部声明小结》在Python文件的顶部声明编码通常是必须的,尤其是在处理非ASCII字符时,下面就来介绍一下两种头部文件声明,具有一定的参考价值,感兴趣的可以了解一下... 目录一、# coding=utf-8二、#!/usr/bin/env python三、运行Python程序四、

无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案

《无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案》:本文主要介绍了无法启动此程序,详细内容请阅读本文,希望能对你有所帮助... 在计算机使用过程中,我们经常会遇到一些错误提示,其中之一就是"api-ms-win-core-path-l1-1-0.dll丢失

Qt之QMessageBox的具体使用

《Qt之QMessageBox的具体使用》本文介绍Qt中QMessageBox类的使用,用于弹出提示、警告、错误等模态对话框,具有一定的参考价值,感兴趣的可以了解一下... 目录1.引言2.简单介绍3.常见函数4.按钮类型(QMessage::StandardButton)5.分步骤实现弹窗6.总结1.引言

Qt中Qfile类的使用

《Qt中Qfile类的使用》很多应用程序都具备操作文件的能力,包括对文件进行写入和读取,创建和删除文件,本文主要介绍了Qt中Qfile类的使用,具有一定的参考价值,感兴趣的可以了解一下... 目录1.引言2.QFile文件操作3.演示示例3.1实验一3.2实验二【演示 QFile 读写二进制文件的过程】4.

SpringBoot后端实现小程序微信登录功能实现

《SpringBoot后端实现小程序微信登录功能实现》微信小程序登录是开发者通过微信提供的身份验证机制,获取用户唯一标识(openid)和会话密钥(session_key)的过程,这篇文章给大家介绍S... 目录SpringBoot实现微信小程序登录简介SpringBoot后端实现微信登录SpringBoo

uniapp小程序中实现无缝衔接滚动效果代码示例

《uniapp小程序中实现无缝衔接滚动效果代码示例》:本文主要介绍uniapp小程序中实现无缝衔接滚动效果的相关资料,该方法可以实现滚动内容中字的不同的颜色更改,并且可以根据需要进行艺术化更改和自... 组件滚动通知只能实现简单的滚动效果,不能实现滚动内容中的字进行不同颜色的更改,下面实现一个无缝衔接的滚动

Java使用WebView实现桌面程序的技术指南

《Java使用WebView实现桌面程序的技术指南》在现代软件开发中,许多应用需要在桌面程序中嵌入Web页面,例如,你可能需要在Java桌面应用中嵌入一部分Web前端,或者加载一个HTML5界面以增强... 目录1、简述2、WebView 特点3、搭建 WebView 示例3.1 添加 JavaFX 依赖3

防止SpringBoot程序崩溃的几种方式汇总

《防止SpringBoot程序崩溃的几种方式汇总》本文总结了8种防止SpringBoot程序崩溃的方法,包括全局异常处理、try-catch、断路器、资源限制、监控、优雅停机、健康检查和数据库连接池配... 目录1. 全局异常处理2. 使用 try-catch 捕获异常3. 使用断路器4. 设置最大内存和线

在React聊天应用中实现图片上传功能

《在React聊天应用中实现图片上传功能》在现代聊天应用中,除了文字和表情,图片分享也是一个重要的功能,本文将详细介绍如何在基于React的聊天应用中实现图片上传和预览功能,感兴趣的小伙伴跟着小编一起... 目录技术栈实现步骤1. 消息组件改造2. 图片预览组件3. 聊天输入组件改造功能特点使用说明注意事项

使用Python创建一个功能完整的Windows风格计算器程序

《使用Python创建一个功能完整的Windows风格计算器程序》:本文主要介绍如何使用Python和Tkinter创建一个功能完整的Windows风格计算器程序,包括基本运算、高级科学计算(如三... 目录python实现Windows系统计算器程序(含高级功能)1. 使用Tkinter实现基础计算器2.