QT網(wǎng)絡(luò)編程Tcp下C/S架構(gòu)的即時(shí)通信實(shí)例
先寫一個(gè)客戶端,實(shí)現(xiàn)簡單的,能加入聊天,以及加入服務(wù)器的界面。
#ifndef TCPCLIENT_H #define TCPCLIENT_H #include <QDialog> #include <QListWidget> #include <QLineEdit> #include <QPushButton> #include <QLabel> #include <QGridLayout> #include <QtNetWork/QHostAddress> #include <QtNetWork/QTcpSocket> class TcpClient : public QDialog { Q_OBJECT public: TcpClient(QWidget *parent = 0,Qt::WindowFlags f=0); ~TcpClient(); private: QListWidget *contentListWidget; QLineEdit *sendLineEdit; QPushButton *sendBtn; QLabel *userNameLabel; QLineEdit *userNameLineEdit; QLabel *serverIPLabel; QLineEdit *serverIPLineEdit; QLabel *portLabel; QLineEdit *portLineEdit; QPushButton *enterBtn; QGridLayout *mainLayout; bool status; int port; QHostAddress *serverIP; QString userName; QTcpSocket *tcpSocket; public slots: void slotEnter(); void slotConnected(); void slotDisconnected(); void dataReceived(); void slotSend(); }; #endif // TCPCLIENT_H
有一個(gè)加入服務(wù)器的按鈕,還有一個(gè)發(fā)送消息的按鈕,在頭文件,先定義兩個(gè)函數(shù)。
#include "tcpclient.h" #include <QMessageBox> #include <QHostInfo> TcpClient::TcpClient(QWidget *parent,Qt::WindowFlags f) : QDialog(parent,f) { setWindowTitle(tr("TCP Client")); contentListWidget = new QListWidget; sendLineEdit = new QLineEdit; sendBtn = new QPushButton(tr("send")); userNameLabel = new QLabel(tr("name")); userNameLineEdit = new QLineEdit; serverIPLabel = new QLabel(tr("server")); serverIPLineEdit = new QLineEdit; portLabel = new QLabel(tr("port")); portLineEdit = new QLineEdit; enterBtn= new QPushButton(tr("join chat")); mainLayout = new QGridLayout(this); mainLayout->addWidget(contentListWidget,0,0,1,2); mainLayout->addWidget(sendLineEdit,1,0); mainLayout->addWidget(sendBtn,1,1); mainLayout->addWidget(userNameLabel,2,0); mainLayout->addWidget(userNameLineEdit,2,1); mainLayout->addWidget(serverIPLabel,3,0); mainLayout->addWidget(serverIPLineEdit,3,1); mainLayout->addWidget(portLabel,4,0); mainLayout->addWidget(portLineEdit,4,1); mainLayout->addWidget(enterBtn,5,0,1,2); status = false; port = 8010; portLineEdit->setText(QString::number(port)); serverIP =new QHostAddress(); connect(enterBtn,SIGNAL(clicked()),this,SLOT(slotEnter())); connect(sendBtn,SIGNAL(clicked()),this,SLOT(slotSend())); sendBtn->setEnabled(false); } TcpClient::~TcpClient() { } void TcpClient::slotEnter() { if(!status) { QString ip = serverIPLineEdit->text(); if(!serverIP->setAddress(ip)) { QMessageBox::information(this,tr("error"),tr("server ip address error!")); return; } if(userNameLineEdit->text()=="") { QMessageBox::information(this,tr("error"),tr("User name error!")); return; } userName=userNameLineEdit->text(); tcpSocket = new QTcpSocket(this); connect(tcpSocket,SIGNAL(connected()),this,SLOT(slotConnected())); connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(slotDisconnected())); connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(dataReceived())); tcpSocket->connectToHost(*serverIP,port); status=true; } else { int length=0; QString msg=userName+tr(":Leave Chat Room"); if((length=tcpSocket->write(msg.toLatin1(),msg.length()))!=msg. length()) { return; } tcpSocket->disconnectFromHost(); status=false; } } void TcpClient::slotConnected() { sendBtn->setEnabled(true); enterBtn->setText(tr("離開")); int length=0; QString msg=userName+tr(":Enter Chat Room"); if((length=tcpSocket->write(msg.toLatin1(),msg.length()))!=msg.length()) { return; } } void TcpClient::slotSend() { if(sendLineEdit->text()=="") { return ; } QString msg=userName+":"+sendLineEdit->text(); tcpSocket->write(msg.toLatin1(),msg.length()); sendLineEdit->clear(); } void TcpClient::slotDisconnected() { sendBtn->setEnabled(false); enterBtn->setText(tr("join chat")); } void TcpClient::dataReceived() { while(tcpSocket->bytesAvailable()>0) { QByteArray datagram; datagram.resize(tcpSocket->bytesAvailable()); tcpSocket->read(datagram.data(),datagram.size()); QString msg=datagram.data(); contentListWidget->addItem(msg.left(datagram.size())); } }
實(shí)現(xiàn)界面布局。在Enter槽函數(shù)中,確定加入還是離開的服務(wù)器的功能。如果加入了,就將消息,寫到tcpsocket中,構(gòu)造消。
服務(wù)端的頭文件:
#ifndef TCPSERVER_H #define TCPSERVER_H #include <QDialog> #include <QListWidget> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QGridLayout> #include "server.h" class TcpServer : public QDialog { Q_OBJECT public: TcpServer(QWidget *parent = 0,Qt::WindowFlags f=0); ~TcpServer(); private: QListWidget *ContentListWidget; QLabel *PortLabel; QLineEdit *PortLineEdit; QPushButton *CreateBtn; QGridLayout *mainLayout; int port; Server *server; public slots: void slotCreateServer(); void updateServer(QString,int); }; #endif // TCPSERVER_H
這是服務(wù)端的界面的,把消息顯示而已。實(shí)現(xiàn)這個(gè)布局。
#include "tcpserver.h" TcpServer::TcpServer(QWidget *parent,Qt::WindowFlags f) : QDialog(parent,f) { setWindowTitle(tr("TCP Server")); ContentListWidget = new QListWidget; PortLabel = new QLabel(tr(" port")); PortLineEdit = new QLineEdit; CreateBtn = new QPushButton(tr("create chat")); mainLayout = new QGridLayout(this); mainLayout->addWidget(ContentListWidget,0,0,1,2); mainLayout->addWidget(PortLabel,1,0); mainLayout->addWidget(PortLineEdit,1,1); mainLayout->addWidget(CreateBtn,2,0,1,2); port=8010; PortLineEdit->setText(QString::number(port)); connect(CreateBtn,SIGNAL(clicked()),this,SLOT(slotCreateServer())); } TcpServer::~TcpServer() { } void TcpServer::slotCreateServer() { server = new Server(this,port); connect(server,SIGNAL(updateServer(QString,int)),this,SLOT(updateServer(QString,int))); CreateBtn->setEnabled(false); } void TcpServer::updateServer(QString msg,int length) { ContentListWidget->addItem(msg.left(length)); }
創(chuàng)建TCP的套接字,以便實(shí)現(xiàn)服務(wù)端和客戶端的通信。
#ifndef TCPCLIENTSOCKET_H #define TCPCLIENTSOCKET_H #include <QtNetWork/QTcpSocket> #include <QObject> class TcpClientSocket : public QTcpSocket { Q_OBJECT public: TcpClientSocket(); signals: void updateClients(QString,int); void disconnected(int); protected slots: void dataReceived(); void slotDisconnected(); }; #endif // TCPCLIENTSOCKET_H
以上是頭文件,具體的是:
#include "tcpclientsocket.h" TcpClientSocket::TcpClientSocket() { connect(this,SIGNAL(readyRead()),this,SLOT(dataReceived())); connect(this,SIGNAL(disconnected()),this,SLOT(slotDisconnected())); } void TcpClientSocket::dataReceived() { while(bytesAvailable()>0) { int length = bytesAvailable(); char buf[1024]; read(buf,length); QString msg=buf; emit updateClients(msg,length); } } void TcpClientSocket::slotDisconnected() { emit disconnected(this->socketDescriptor()); }
實(shí)現(xiàn)服務(wù)器,頭文件:
#ifndef SERVER_H #define SERVER_H #include <QtNetWork/QTcpServer> #include <QObject> #include "tcpclientsocket.h" class Server : public QTcpServer { Q_OBJECT public: Server(QObject *parent=0,int port=0); QList<TcpClientSocket*> tcpClientSocketList; signals: void updateServer(QString,int); public slots: void updateClients(QString,int); void slotDisconnected(int); protected: void incomingConnection(int socketDescriptor); }; #endif // SERVER_H
#include "server.h" Server::Server(QObject *parent,int port) :QTcpServer(parent) { listen(QHostAddress::Any,port); } void Server::incomingConnection(int socketDescriptor) { TcpClientSocket *tcpClientSocket = new TcpClientSocket; connect(tcpClientSocket,SIGNAL(updateClients(QString,int)),this,SLOT(updateClients(QString,int))); connect(tcpClientSocket,SIGNAL(disconnected(int)),this,SLOT(slotDisconnected(int))); tcpClientSocket->setSocketDescriptor(socketDescriptor); tcpClientSocketList.append(tcpClientSocket); } void Server::updateClients(QString msg,int length) { emit updateServer(msg,length); for(int i=0;i<tcpClientSocketList.count();i++) { QTcpSocket *item = tcpClientSocketList.at(i); if(item->write(msg.toLatin1(),length)!=length) { continue; } } } void Server::slotDisconnected(int descriptor) { for(int i=0;i<tcpClientSocketList.count();i++) { QTcpSocket *item = tcpClientSocketList.at(i); if(item->socketDescriptor()==descriptor) { tcpClientSocketList.removeAt(i); return; } } return; }
實(shí)現(xiàn)后的界面:
以上這篇QT網(wǎng)絡(luò)編程Tcp下C/S架構(gòu)的即時(shí)通信實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持我們。
上一篇:ubuntu系統(tǒng)下C++調(diào)用matlab程序的方法詳解
欄 目:C語言
下一篇:C++ STL入門教程(3) deque雙向隊(duì)列使用方法
本文標(biāo)題:QT網(wǎng)絡(luò)編程Tcp下C/S架構(gòu)的即時(shí)通信實(shí)例
本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/1233.html
您可能感興趣的文章
- 01-10大數(shù)(高精度數(shù))模板(分享)
- 01-10深入解析Linux下\r\n的問題
- 01-10Linux C 獲取進(jìn)程退出值的實(shí)現(xiàn)代碼
- 01-10解析Linux下的時(shí)間函數(shù):設(shè)置以及獲取時(shí)間的方法
- 01-10深入探討linux下進(jìn)程的最大線程數(shù)、進(jìn)程最大數(shù)、進(jìn)程打開的文
- 01-10基于linux下獲取時(shí)間函數(shù)的詳解
- 01-10深入sizeof的使用詳解
- 01-10Linux下semop等待信號(hào)時(shí)出現(xiàn)Interrupted System Call錯(cuò)誤(EINTR)解決方法
- 01-10深入解析C中的數(shù)值與真假
- 01-10用c語言實(shí)現(xiàn)冒泡排序,選擇排序,快速排序


閱讀排行
本欄相關(guān)
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達(dá)
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對(duì)數(shù)函數(shù)的表達(dá)式 c語言中對(duì)
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求
隨機(jī)閱讀
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 01-10delphi制作wav文件的方法
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10C#中split用法實(shí)例總結(jié)
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10使用C語言求解撲克牌的順子及n個(gè)骰子
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 08-05織夢dedecms什么時(shí)候用欄目交叉功能?
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 04-02jquery與jsp,用jquery