基于Qt简单聊天程序-具体步骤-详细注释
基于qt编写的c,s模型的
简单聊天程序
开发Qt工具
一.创建
工程
路基工程安全技术交底工程项目施工成本控制工程量增项单年度零星工程技术标正投影法基本原理
1,选择新建工程
2 选择Qt4 Gui Application工程。(带UI界面编辑的工程)
3 取工程名 C_S_Socket。路径随意,不要有任何中文 Next
4 默认即可,Next(这是为此次工程选择要添加的头文件。我们不需要其他的功能。默认)
5 Base class 选择QDialog。Class name 改 MainDlg。 Next(我们是基于Qt界面编程的嘛。所以就选QDialog Qt窗口类噻)
6 Finish 完成(这里是编辑器告诉我们生成了如下文件)
二.画界面
1 点击maindlg.ui 进入主界面窗体
设计
领导形象设计圆作业设计ao工艺污水处理厂设计附属工程施工组织设计清扫机器人结构设计
成如下
2 设置各个控件的对象名(不能同名,系统用对象名找到控件。命名
规范
编程规范下载gsp规范下载钢格栅规范下载警徽规范下载建设厅规范下载
方便自己识别)
{
服务器单选框:radioButton_Server
客户端单选框:radioButton_Client
IP地址框:lineEdit_Address
用户名框:lineEdit_Name
离开按钮:wayButton
进入按钮:enterButton
}
3 创建一个窗体类,用于发送接收信息的窗体
选择窗体样式。
修改类名 chat,下一步完成~(chat:聊天的意思)
4 第二窗体设计如下
窗体控件对象名如下
{
显示信息框:showMessageEdit
输入信息框:writeMessageEdit
用户名显示列
表
关于同志近三年现实表现材料材料类招标技术评分表图表与交易pdf视力表打印pdf用图表说话 pdf
:onlineMessageList
关于按钮:aboutButton
发送按钮:sendButton
}
界面等操作到此结束~~2013年12月8日16:47:31
代码贴在后面。
注意:代码写完后编译会出错~在C_S_Socket.pro 工程文件的最后加上 QT +=
network 编译就不会出错了 (不知道什么意思,难道是为Qt加入网络的支持,)
代码
maindlg.h
#ifndef MAINDLG_H
#define MAINDLG_H
#include
namespace Ui {
class MainDlg;
}
class MainDlg : public QDialog {
Q_OBJECT
public:
MainDlg(QWidget *parent = 0);
~MainDlg();
bool m_bool_server;//判断选择的方式
protected:
void changeEvent(QEvent *e);
signals://信号
void showChatWindow();
void sendEnterMessage(QString, QString); private:
Ui::MainDlg *ui;
public slots://槽
void enterSlot();
void OnSelectServer();
void OnSelectClient();
};
#endif // MAINDLG_H
maindlg.cpp
#include "maindlg.h"
#include "ui_maindlg.h"
#include
MainDlg::MainDlg(QWidget *parent) :
QDialog(parent),
ui(new Ui::MainDlg)
{
ui->setupUi(this);
//离开按钮点击事件的连接
connect(ui->awayButton, SIGNAL(clicked()),qApp, SLOT(quit()));
//进入按钮点击事件的连接
connect(ui->enterButton, SIGNAL(clicked()), this, SLOT(enterSlot()));
//选择服务器单选按钮点击事件的连接
connect(ui->radioButton_Server, SIGNAL(clicked()), this, SLOT(OnSelectServer()));
//选择客户端单选按钮点击事件的连接
connect(ui->radioButton_Client, SIGNAL(clicked()), this, SLOT(OnSelectClient()));
}
MainDlg::~MainDlg()
{
delete ui;
}
/*
*选择服务器单选按钮的点击消息
*/
void MainDlg::OnSelectServer()
{
m_bool_server = true;
ui->lineEdit_Address->setText("");
if (ui->lineEdit_Name->text().isEmpty()|| ui->lineEdit_Name->text()=="Client")
ui->lineEdit_Name->setText("Server"); }
/*
*选择客户端单选按钮的点击消息
*/
void MainDlg::OnSelectClient()
{
m_bool_server = false;
ui->lineEdit_Address->setText("127.0.0.1");
if (ui->lineEdit_Name->text().isEmpty() || ui->lineEdit_Name->text()=="Server")
ui->lineEdit_Name->setText("Client"); }
void MainDlg::changeEvent(QEvent *e) {
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void MainDlg::enterSlot()
{
if (ui->lineEdit_Name->text().isEmpty())
{
QMessageBox mess;
mess.setFont(QFont("Sans Serif", 12, 50));
mess.warning(this,
QString::fromLocal8Bit("出错"),
QString::fromLocal8Bit("请输入正确的昵称,谢谢!"));
return;
}
//发射信号
emit sendEnterMessage(ui->lineEdit_Name->text(), ui->lineEdit_Address->text());
emit showChatWindow();
}
chat.h
#ifndef CHAT_H
#define CHAT_H
#include
#include "maindlg.h"
#include
#include //Tcp
协议
离婚协议模板下载合伙人协议 下载渠道分销协议免费下载敬业协议下载授课协议下载
的服务器监听连接类
#include //Tcp协议的Socket类 #include
namespace Ui {
class chat;
}
class chat : public QDialog {
Q_OBJECT
public:
chat(QWidget *parent = 0);
~chat();
void socketServer();//启动服务器监听连接
void socketClient(QString host);//与服务器连接
MainDlg *p_my_dlg;//主界面指针
int port;//端口号
QString m_str_userName;//用户名
bool m_bool_server;//是服务器还是客户端
//Tcp协议的服务器Socket类
QTcpServer *m_p_server;//Tcp协议的服务器监听连接类
QTcpSocket *m_p_serverSocket;//服务器Socket
QTcpSocket *m_p_clientSocket;//客户端Socket
QDateTime nowDateTime;//时间
protected:
void changeEvent(QEvent *e);
private:
Ui::chat *ui;
public slots://槽
void showAndHideSlot();//显示本窗体关闭主窗体
void changeButtonStateSlot();//如果输入框为空,则发送按钮不能使用
void createAboutSlot();//关于信息
void enterSlot(QString name, QString host);//选择服务器或客户端
void newConnectionSlot();//连接来时,服务器与客户端创建连接
void newDataSlot();//有数据来时
void deleNameSlot();//
void addSlot();
void appendMessageSlot();
};
#endif // CHAT_H
chat.cpp #include "chat.h"
#include "ui_chat.h"
#include
chat::chat(QWidget *parent) :
QDialog(parent),
ui(new Ui::chat)
{
ui->setupUi(this);//设置 UI设计的界面的控件
m_p_server = NULL;
m_p_serverSocket = NULL;
m_p_clientSocket = NULL;
p_my_dlg = new MainDlg;//主界面
p_my_dlg->show(); //显示主界面
/*
*连接信号
*/
//主窗体中显示本窗体信号
connect(p_my_dlg, SIGNAL(showChatWindow()), this, SLOT(showAndHideSlot()));
connect(p_my_dlg, SIGNAL(sendEnterMessage(QString , QString)),
this,SLOT(enterSlot(QString , QString )));
connect(ui->writeMessageEdit, SIGNAL(textChanged()), this,
SLOT(changeButtonStateSlot()));
connect(ui->aboutButton, SIGNAL(clicked()), this, SLOT(createAboutSlot()));
connect(ui->sendButton, SIGNAL(clicked()), this, SLOT(appendMessageSlot()));
}
chat::~chat()
{
delete ui;
}
//本窗体创建时由系统自动调用
void chat::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);//设置本船体的一些属性
break;
default:
break;
}
}
//显示关闭主窗体,显示本窗体
void chat::showAndHideSlot()
{
delete p_my_dlg;
this->show();
}
//显示关于信息
void chat::createAboutSlot()
{
QMessageBox mess;
mess.setFont(QFont("Sans Serif", 12, 50));
mess.warning(this,
QString::fromLocal8Bit("关于"),
QString::fromLocal8Bit("基于qt编写的c,s模型的简单聊天程序"));
}
//根据选择p_my_dlg->m_bool_server 选择相应操作 void chat::enterSlot(QString name, QString host) {
port = 22222;//设置Socket端口号
m_bool_server = p_my_dlg->m_bool_server;//选择状态传送
if (m_bool_server)
{
socketServer();
}
else
{
socketClient(host);
}
ui->sendButton->setDisabled(false);//发送按钮不能使用
m_str_userName = name;
ui->onlineMessageList->addItem(name); }
//如果输入框为空,则发送按钮不能使用 void chat::changeButtonStateSlot()
{
bool boo_dis = ui->writeMessageEdit->toPlainText().isEmpty();
ui->sendButton->setDisabled(boo_dis); }
//发送信息
void chat::appendMessageSlot()
{
//获取输入框内容,然后清空
QString content = ui->writeMessageEdit->toPlainText();
if (content.isEmpty())
{
QMessageBox::warning(this, "出错", QString::fromLocal8Bit("发送的内容不能为空
"));
return;
}
nowDateTime = QDateTime::currentDateTime();//获取时间
//按指定格式拼合字符串
ui->showMessageEdit->append(
QString("\n[%1] %2 %3\n%4")
.arg(nowDateTime.toString("yyyy-MM-dd hh:mm:ss"))
.arg(m_str_userName)
.arg(QString::fromLocal8Bit("说道:"))
.arg(content) );
QDataStream out;//流
if (m_bool_server)
{
out.setDevice(m_p_serverSocket);
}
else
{
out.setDevice(m_p_clientSocket);
}
int mark = 0;//普通信息代号
//发送代号+用户名=信息
out << mark;
out << m_str_userName << content;
ui->writeMessageEdit->clear(); }
//创建服务器Socket 监听连接
void chat::socketServer()
{
m_p_server = new QTcpServer(this);//创建TCP 服务器用于监听socket连接
m_p_serverSocket = new QTcpSocket(this);//创建套接字
m_p_server->listen(QHostAddress::Any, port);//监听 socket连接
//设置 有新连接信号,触发函数
connect(m_p_server, SIGNAL(newConnection()), this, SLOT(newConnectionSlot())); }
//有新的连接时。槽
void chat::newConnectionSlot()
{
m_p_serverSocket = m_p_server->nextPendingConnection();
//有数据来时,
connect(m_p_serverSocket, SIGNAL(readyRead()), this, SLOT(newDataSlot()));
connect(m_p_serverSocket, SIGNAL(disconnected()), this, SLOT(deleNameSlot())); }
//创建客户端Socket 与服务器连接
void chat::socketClient(QString host)
{
m_p_clientSocket = new QTcpSocket(this);
m_p_clientSocket->connectToHost(host, port);
//当成功连接时,名字list框中加入用户名
connect(m_p_clientSocket, SIGNAL(connected()), this, SLOT(addSlot()));
connect(m_p_clientSocket, SIGNAL(readyRead()), this, SLOT(newDataSlot()));
connect(m_p_clientSocket, SIGNAL(disconnected()), this, SLOT(deleNameSlot())); }
//在名字list框中加入用户名
void chat::addSlot()
{
QString content;
QDataStream out(m_p_clientSocket);//Qt socket 数据传输的方式
int mark = 11;
//把socket看成流使用
out << mark;//发送代号11+用户名, 告诉服务器,连接成功了,
out << m_str_userName << content;
}
//接收信息
void chat::newDataSlot()
{
int mark;
QString hisName;
QString content;
QDataStream in;//流对象
if (m_bool_server)
{
in.setDevice(m_p_serverSocket);//把服务器的Sokcet当成流
}
else
{
in.setDevice(m_p_clientSocket);//把客户端的Sokcet当成流
}
in >> mark;//读取代号
// 如果代号是11,则是客户端加入。添加用户名
if (mark == 11) //addList
{
in >> hisName >> content;
if (content.isEmpty())
{
ui->onlineMessageList->addItem(hisName);//添加用户名
if (m_bool_server)
{
QString content;
QDataStream out(m_p_serverSocket);//执行相同代号,让客户端也添加用
户名
int mark = 11;
out << mark;
out << m_str_userName<< content;
}
}
return;
}
//代号0.普通信息
else if (mark == 0) //message
{
in >> hisName >> content;//读信息
nowDateTime = QDateTime::currentDateTime();//时间
//按照指定格式,拼合 显示信息,
ui->showMessageEdit->append(
QString("\n[%1] %2 %3\n%4")
.arg(nowDateTime.toString("yyyy-MM-dd hh:mm:ss"))
.arg(hisName)
.arg(QString::fromLocal8Bit("说道:"))
.arg(content) );
return;
}
}
//断开连接时,删除用户名
void chat::deleNameSlot()
{
ui->onlineMessageList->takeItem(1); }
main.cpp #include
#include "chat.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
chat *p_chart = new chat;
return a.exec();
}
作者:长沙北邮3G-Z19班 雷建军
2013年12月8日16:51:49