《基于Qt简单聊天程序-具体步骤-详细注释.docx》由会员分享,可在线阅读,更多相关《基于Qt简单聊天程序-具体步骤-详细注释.docx(9页珍藏版)》请在课桌文档上搜索。
1、基于qt编写的c/s模型的简单聊天程序开发Qt工具1,选择新建工程2选择Qt4GuiApplication工程。(带Ul界面编辑的工程)3取工程名C_S_Socket。路径随意,不要有任何中文Next4默认即可,Next(这是为此次工程选择要添加的头文件。我们不需要其他的功能。默认)5 Baseclass选择QDiaIog(IClassname改MainDlgoNext(我们是基于Qt界面编程的嘛。所以就选QDialogQt窗口类嚷)6 Finish完成(这里是编辑器告诉我们生成了如下文件)1点击maindlg.ui进入主界面窗体设计成如下2设置各个控件的对象名(不能同名,系统用对象名找到控件
2、。命名标准方便自己识别)效劳器睢项选择框:radioBu11on_Server客户端雅项选择框:radioButton_CIientIP地址框:lineEdit_Address用户名框:1IneEditName离开按钮:WayButton进入按钮:GnterButton3创立一个窗体类,用于发送接收信息的窗体选择窗体样式。修改类名chat,下一步完成(chat:聊天的意思)4第二窗体设计如下窗体控件对象名如下显示信息框:ShowMessageEdit输入信息框:WritcMessageEdit用户名显示列表:OnIineMeSSageLiSt关于按钮:aboutButton发送按钮:SendB
3、utton界面等操作到此结束!!2023 年 12 月 8 日 16:47:31代码贴在后面。7/昆:代码写完后编译会出错!在C_S_Socket.pro工程文件的最后加上QT+=network编译就不会出错了(不知道什么意思,难道是为Qt参加网络的支持?)代码#ifndefMAINDLGH#defineMAINDLG_H#includcnamespaceUiclassMainDlg;classMainDlg:publicQDialogQ_OBJECTpublic:MainDlg(QWidget*parent=O);-MainDlgO;boolm_bool_server;判断选择的方式prot
4、ected:voidchangeEvent(QEvcnt*e);voidshowChatWindow();voidsendEnterMessage(QString,QString);private:Ui:MainDlg*ui;voidenterSlot();voidOnSelectServerO;voidOnSelectClientO;;#endifMAINDLG_H#includemaindlg.h,r#include,uLmaindlg.h,#includeMainDlg:MainDlg(QWidget*parent):QDialog(parent),ui(newUi:MainDlg)ui
5、-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,SIGNA
6、L(clickcd(),this,SLOT(OnSelectClient();MainDlg-MainDIgOdeleteui;产*选择效劳器单项选择按钮的点击消息voidMainDlg:OnSelectServer()m_bool_server=true;ui-lineEdicAddress-setTcxt(,n,);if(ui-lineEdit-Namc-text().isEmpty()ui-lincEdit_Name-text()=,Clicnt)ui-lineEdicName-setText(,Server);*选择客户端单项选择按钮的点击消息voidMainDlg:OnSclectC
7、lient()m_booLserver=false;ui-lineEdit-Address-setText(,l27.0.0.);if(ui-lineEdit_Name-text().isEmpty()ui-lineEdit_Name-text()=,ServerM)ui-lineEdit_Name-setText(Client);voidMainDlg:changeEvent(QEvent*e)QDialog:changeEvent(e);switch(e-type()caseQEvent:LanguageChange:ui-retranslateUi(this);break;default
8、:break;voidMainDlg:enterSlot()if(ui-lineEdit_Name-text().isEmptyO)QMessageBoxmess;mess.setFont(QFont(SansSerif12,50);mess.warning(this,QString:ifroniLocalSBitC11出错),QString:zfronLocal8Bit(,请输入正确的昵称,谢谢!);return;发射信号emitsendEterMessage(iL-lieEdit-Nae-text()1ui-lineEtext();emitshowChatWindow();#ifndefC
9、HAT_HdefineCHAT_H#include#includemaindlg.h,r#include#includelcp协议的效劳器监听连接类#includeTcp协议的Socket类#incluclenamespaceUiclasschat;ClaSSchat:publicQDialogQ_OBJECTpublic:chat(QWidget*parunt=0);chat();voidSOCkUtSerVCr0;启动效劳器监听连接voidsocketCliet(QStringhost)/与效劳器连接MainDlg*p_my_dlg;主界面指针intPOrtJ/端口号QStringm_st
10、r_userName;用户名boolrn_bool_servur;是效劳器还是客户端/cp协议的效劳器Socket类QTcpServer*m_p_server;/Tcp协议的效劳器监听连接类QTcpSocket*m_p_serverSoket;效劳器SocketQTcpSocket*m_p_clientSOCket;客户端SocketQDateTimenowDateTie;时间protected:voidchangeEvent(QEvent*e);private:Ui:Chat*ui;voidShOWAndHideSlOt();显示本窗体关闭主窗体voidChangCBUttOnStatCSI
11、Ot();/如果输入框为空,那么发送按钮不能使用voidCreateAboUtSIOt();关于信息voidcnterSlot(QStringname,QStringhost);选择效劳器或客户端voidncwConncctionSlot()y/连接来时,效劳器与客户端创立连接voidnewDataSlot();有数据来时voiddcleNameSlot();/voidaddSlot();voidappcndMessagcSlot();;#endifCHAT-H#includechat.h#includeui_chat.h#includechat:xhat(QWidget*parent):QD
12、ialog(parent),ui(newUi:chat)Iui-setupUi(this);设置UI设计的界面的控件m_p_server=NULL;m_p_serverSocket=NULL;m_p_c1ientSocket=NULL;p_my_dlg=newMainDIg,主界面p_my_dlg-show();显示主界面*连接信号主窗体中显示本窗体信号connect(p_my_dlg,SlGNAL(ShowChatWindowO),this,SLOT(showAndHideSlotO);ConneCt(p_my_dlg,SIGNAL(sendEnterMessage(QString,QStr
13、ing),this,SLOT(enterSlot(QString,QString);connect(ui-writeMessageEdit,SIGNAL(IextChangedO),this,SLOT(ChangeButtonStateSIotO);COnneCt(Ui-XiboutButton,SIGNAL(CIiCkUd(),this,SLOT(createAboutSlot();connect(ui-sendButton,SlGNAL(clicked(),this,SLOT(appendMessageSlot();Chat:chat()deleteui;本窗体创立时由系统自动调用void
14、chat:xhangeEvent(QEvent*e)QDialogixhangeEvent(C);switch(e-type()caseQEventziLanguageChange:ui-rctranslatcUi(this);/设置本船体的些属性break;default:break;显示关闭主窗体,显示本窗体voidChat:ShOWAndHideSIUt()deletep_my_dlg;this-show();显示关于信息voidchat:XreateAboutSlotOQMessageBoxmess;mess.setFont(QFont(,rSansSerif,12,50);mess.
15、warning(this,QStrirg=fromLal8Bit(关于),QString:fromLocal8Bit(基于qt编写的C/S模型的简单聊天程序);根据选择p_my_dlg-m_bool_server选择相应操作voidchat:enterSlot(QStringname,QStringhost)(port=22222;设置Socket端口号m_bool_server=p_my_dlg-m_bool_server;选择状态传送if(m_bool_server)socketServer();elsesocketClient(host);1ui-sendButton-setDisabl
16、ed(fake);发送按钮不能使用m_str_userName=name;ui-onlineMessageList-addItem(name);如果输入框为空,那么发送按钮不能使用voidchat:IchangcButtonStateSlotOblboo_dis=ui-writcMessageEdit-toPlainText().isEmpty();ui-sendButton-setDisablcd(boo_dis);发送信息voidchat:appcndMessageSlot()获取输入框内容,然后清空QStringcontent=ui-writeMessageEdit-toPlainTex
17、t();if(contcnt.isEmpty()QMeSSageBox:Warning(this,出错,QString:frumLocal8Bit(”发送的内容不能为空return;nowDateTime=QDateTimc:CUITCntDatCTime();获取时间按指定格式拼合字符串ui-showMessageEdit-append(QString(,n%l%2%3n%4,).arg(nowDateTime.toString(,yyyy-MM-ddhh:mm:ss”).arg(m_str_userName).arg(QString:zfiomLocal8BitC,说道:).arg(con
18、tent);QDataStreamOUt;/流if(m_bool_server)out.setDevice(m_p_serverSocket);elseout.setDevice(m_p_clientSocket);intmark=0;普通信息代号发送代号+用户名=信息outmark;outm_str_userNamecontent;ui-writeMessageEdit-clear();创立效劳器SOCket监听连接voidchat:socketServer()m_p_server=newQTCPSerVei(this);创立TCP效劳器用于监听SOCket连接m_p_serverSocke
19、t=newQTCPSOCkCt(this);创立套接字m_p_server-listen(QHostAddress:Any,Port)监听socket连接设置有新连接信号,触发函数connect(m_p_server,SIGNAL(newConnection(),this,SLOT(newConncctionSlot();有新的连接时。槽voidchat:newConnectionSlot()m_p一SCrVerSoCkCt=m_p_server-nextPcndingConnection();有数据来时,connect(m_p_serverSocket,SIGNAL(readyRcad(),
20、this,SLOT(newDataSlot();connect(m_p_serverSocket,SlGNAL(disconnected。),this,SLOT(JeleNameSlotO);创立客户端SOCkUt与效劳器连接voidchat:IsockctClicnUQStiinghost)m_p_clientSocket=newQTcpSockeKthis);11VP-ClientSocket-connectToHost(host,port);/当成功连接时,名字IiSt框中参加用户名connect(m_p_clientSocket,SIGNAL(ConneCted(),this,SLOT
21、(addSlot();connect(m_p_clientSocket,SIGNAL(readyRcad(),this,SLOT(newDataSlot();connect(m_p_clientSocket,SIGNAL(disconnectcd(),this,SLOT(deleNamcSlot();在名字IiSt框中参加用户名voidchat:addSlot()IQStringcontent;QDataStreamout(m_p_clientSocket);/Qtsocket数据传输的方式intmark=11;把socket看成流使用outmark;发送代号11+用户名,告诉效劳器,连接成功
22、了,outm_str_userNameonlineMessageList-addItem(hisName)JU11户名if(m_bool_server)QStringcontent;QDataStrcamout(m_p_serverSockct);执行相同代号,让客户端也添加用户名intmark=11;outmark;outm_str_userNameshowMessageEdit-append(QString(,n%l%2%3n%4).arg(nowDateTime.toString(,yyyy-MM-ddhh:mm:ss”).arg(hisName).arg(QStringkfmLocal8Bit(说道:).arg(content);return;/断开连接时,删除用户名voidchat:deleNameSlot()Iui-onlineMessageList-takeItem(1);#include#include,chaLhintmain(intargc,char*argv)QApplicatioiia(argc,agv);chat*p_chart=newchat;returna.exec();长沙北邮3GZ19班雷建军2023年12月8日16:51:49