基于tcp協议的网络聊天室.docVIP

  • 9
  • 0
  • 约5.02千字
  • 约 6页
  • 2016-11-27 发布于重庆
  • 举报
基于tcp協议的网络聊天室

青岛科技大学信息科学技术学院实验报告 ---------------------------------------------------------------------------------------------------------------------- 班级: 软件113 姓名: 蒋栋 学号: 1108050328 成绩: 实验名称: 基于TCP的网络聊天室 1.实验目的: 掌握TCP通讯协议、掌握QTcpSocket 2.实验内容: 使用Qt的QtcpSocket实现简单的网络聊天程序,范例如图: 包括拂去其程序和客户端程序,服务端程序可以创建一个聊天室,客户端程序可以输入登陆的用户名、服务器地址以及使用的端口号,然后进入聊天室,聊天室中的每一位用户均可以看见发布的信息。 3.实验方法: 使用Qt的QtcpSocket,参考Qt网络编程实验。 4.实验过程 tcpServer端 代码: #include dialog.h #include ui_dialog.h Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui-setupUi(this); ui-lineEdit-setText(8010); port=8010; } Dialog::~Dialog() { delete ui; } void Dialog::on_newchat_clicked() { server=new Server(this,port); connect(server,SIGNAL(updateServer(QString,int)),this,SLOT(updateServer(QString,int))); ui-newchat-setEnabled(false); } void Dialog::updateServer(QString msg,int length) { ui-listWidget-addItem (msg.left(length) ); } tcpServer端server.cpp 代码: #include server.h #include QTcpSocket Server::Server(QObject*parent,int port) :QTcpServer(parent) { listen(QHostAddress::Any,port); } void Server::incomingConnection(int socketDescriptor) { TcpclientSocket*tcpClientSocket=new TcpclientSocket(this); connect(tcpClientSocket,SIGNAL(updateClient(QString,int)),this,SLOT(updateClient(QString,int))); connect(tcpClientSocket,SIGNAL(disconnected(int)),this,SLOT(slotDisconnected(int))); tcpClientSocket-setSocketDescriptor(socketDescriptor); tcpClientSocketList.append(tcpClientSocket); } void Server::updateClient(QString msg, int length) { emit updateServer(msg,length); for(int i=0;itcpClientSocketList.count();i++) { QTcpSocket*item=tcpClientSocketList.at(i); if(item-write(msg.toLatin1(),length)!=length) {continue ;}; } } void Server::slotDisconnected(int descriptor) { for(int i=0;itcpClientSocketList.count();i++) { QTcpSocket*item=tcpClientSocketList.at(i); if(it

文档评论(0)

1亿VIP精品文档

相关文档