資源描述:
《基于tcp協(xié)議的網(wǎng)絡(luò)聊天室》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在工程資料-天天文庫(kù)。
1、實(shí)驗(yàn)名稱:基于TCP的網(wǎng)絡(luò)聊天室1?實(shí)驗(yàn)冃的:掌握TCP通訊協(xié)議、掌握QTcpSocket2?實(shí)驗(yàn)內(nèi)容:使用Qt的QtcpSocket實(shí)現(xiàn)簡(jiǎn)單的網(wǎng)絡(luò)聊天程序,范例如圖:包括拂去其程序和客戶端程序,服務(wù)端程序可以創(chuàng)建一個(gè)聊天室,客戶端程序可以輸入登陸的用戶名、服務(wù)器地址以及使用的端口號(hào),然后進(jìn)入聊天室,聊天室中的每一位用戶均可以看見(jiàn)發(fā)布的信息。3?實(shí)驗(yàn)方法:使用Qt的QtcpSocket,參考Qt網(wǎng)絡(luò)編程實(shí)驗(yàn)。4?實(shí)驗(yàn)過(guò)程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()