欢迎来到天天文库
浏览记录
ID:45783425
大小:104.81 KB
页数:7页
时间:2019-11-17
《基于tcp协议的网络聊天室》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、实验名称:基于TCP的网络聊天室1•实验冃的:掌握TCP通讯协议、掌握QTcpSocket2•实验内容:使用Qt的QtcpSocket实现简单的网络聊天程序,范例如图:包括拂去其程序和客户端程序,服务端程序可以创建一个聊天室,客户端程序可以输入登陆的用户名、服务器地址以及使用的端口号,然后进入聊天室,聊天室中的每一位用户均可以看见发布的信息。3•实验方法:使用Qt的QtcpSocket,参考Qt网络编程实验。4•实验过程tcpServer端代码:#include"dialog.h"#include"ui_dialog
2、.hHDialog::Dialog(QWidget^parent):QDialog(parent),ui(newUi::Dialog){ui->setupUi(this);ui->lineEdit->setText(n8010H);port=8010;}Dialog::~Dialog(){deleteui;}voidDialog::on_newchat_clicked(){server=newServer(this,port);connect(server,SIGNAL(updateServer(QString3nt
3、)),this,SLOT(updateServer(QString,int)));ui->newchat->setEnabled(false);}voidDialog::updateServer(QStringmsg,intlength){-ui->listWidget->addItem(msg.left(length));}(tcpServer端server.cpp彳弋码:#includeHserver.hn#includeServer::Server(QObject*parent5intp
4、ort):QTcpServer(parent){listen(QHostAddress::Any,port);}voidServer::incomingConnection(intsocketDescriptor){TcpclientSocket*tcpClientSocket=newTcpclientSocket(this);connect(tcpClientSocket,SIGNAL(updateClient(QString,int)),this,SLOT(updateClient(QStringjnt)));c
5、onnect(tcpClientSocket,SIGNAL(disconnected(int)),this,SLOT(slotDisconnected(int)));tcpClientSocket->setSocketDescriptor(socketDescriptor);tcpClientSocketList.append(tcpClientSocket);}voidServer::updateClient(QStringmsg,intlength){emitupdateServer(msgJength);for
6、(inti=0;iwrite(msg.toLatin1().length)!=length){continue;};}}voidServer::slotDisconnected(intdescriptor){for(inti=0;i7、ocketList.at(i);if(item・>socketDescriptor()==descriptor){tcpClientSocketList.removeAt(i);return;}}return;Tcpclient端代码:#include"dialog.h"#include"ui_dialog.hH#includeDialog::Dialog(QWidget^parent):QDialog(parent),ui(newUi::Dialog){ui->setupUi(this);8、ui->lineEdit_4->setText("8010”);status=false;serverIP=newQHostAddress();port=8010;ui->pb_send->setEnabled(false);Dialog::-Dialog(){deleteui;}voidDialog::on_pb_send_clicked()
7、ocketList.at(i);if(item・>socketDescriptor()==descriptor){tcpClientSocketList.removeAt(i);return;}}return;Tcpclient端代码:#include"dialog.h"#include"ui_dialog.hH#includeDialog::Dialog(QWidget^parent):QDialog(parent),ui(newUi::Dialog){ui->setupUi(this);
8、ui->lineEdit_4->setText("8010”);status=false;serverIP=newQHostAddress();port=8010;ui->pb_send->setEnabled(false);Dialog::-Dialog(){deleteui;}voidDialog::on_pb_send_clicked()
此文档下载收益归作者所有