zoukankan      html  css  js  c++  java
  • Qt TCP网络编程基本教程

    首先介绍一下TCP:(Transmission Control Protocol 传输控制协议)是一种面向连接的、可靠的、基于字节流的传输层通信协议。相比而言UDP,就是开放式、无连接、不可靠的传输层通信协议。 下面,我一次进行客户端和服务器端的QT实现。我的开发环境是:QT Creator 5.7。

    先看下效果图:
    one server---two clients

    一:客户端编程

    QT提供了QTcpSocket类,可以直接实例化一个客户端,可在help中索引如下:

    1 The QTcpSocket class provides a TCP socket. More...
    2 Header      #include <QTcpSocket> 
    3 qmake       QT += network
    4 Inherits:   QAbstractSocket
    5 Inherited By:   QSslSocket

    从这里,我们可以看到,必须要在.pro文件中添加QT += network才可以进行网络编程,否则是访问不到<QTcpSocket>头文件的。 客户端读写相对简单,我们看一下代码头文件:

     1 #ifndef MYTCPCLIENT_H
     2 #define MYTCPCLIENT_H
     3 
     4 #include <QMainWindow>
     5 #include <QTcpSocket>
     6 #include <QHostAddress>
     7 #include <QMessageBox>
     8 namespace Ui {
     9 class MyTcpClient;
    10 }
    11 
    12 class MyTcpClient : public QMainWindow
    13 {
    14     Q_OBJECT
    15 
    16 public:
    17     explicit MyTcpClient(QWidget *parent = 0);
    18     ~MyTcpClient();
    19 
    20 private:
    21     Ui::MyTcpClient *ui;
    22     QTcpSocket *tcpClient;
    23 
    24 private slots:
    25     //客户端槽函数
    26     void ReadData();
    27     void ReadError(QAbstractSocket::SocketError);
    28 
    29     void on_btnConnect_clicked();
    30     void on_btnSend_clicked();
    31     void on_pushButton_clicked();
    32 };
    33 
    34 #endif // MYTCPCLIENT_H

    我们在窗口类中,定义了一个私有成员QTcpSoket *tcpClient。

    1) 初始化QTcpSocket
    在构造函数中,我们需要先对其进行实例化,并连接信号与槽函数:

    1     //初始化TCP客户端
    2     tcpClient = new QTcpSocket(this);   //实例化tcpClient
    3     tcpClient->abort();                 //取消原有连接
    4     connect(tcpClient, SIGNAL(readyRead()), this, SLOT(ReadData()));
    5     connect(tcpClient, SIGNAL(error(QAbstractSocket::SocketError)), 
    6             this, SLOT(ReadError(QAbstractSocket::SocketError)));

    2)建立连接 和 断开连接

    1     tcpClient->connectToHost(ui->edtIP->text(), ui->edtPort->text().toInt());
    2     if (tcpClient->waitForConnected(1000))  // 连接成功则进入if{}
    3     {
    4         ui->btnConnect->setText("断开");
    5         ui->btnSend->setEnabled(true);
    6     }

    a)建立TCP连接的函数:void connectToHost(const QHostAddress &address, quint16 port, OpenMode openMode = ReadWrite)是从QAbstractSocket继承下来的public function,同时它又是一个virtual function。作用为:Attempts to make a connection to address on port port。

    b)等待TCP连接成功的函数:bool waitForConnected(int msecs = 30000)同样是从QAbstractSocket继承下来的public function,同时它又是一个virtual function。作用为:Waits until the socket is connected, up to msecs milliseconds. If the connection has been established, this function returns true; otherwise it returns false. In the case where it returns false, you can call error() to determine the cause of the error.

    上述代码中,edtIP, edtPort是ui上的两个lineEditor,用来填写服务器IP和端口号。btnConnect是“连接/断开”复用按钮,btnSend是向服务器发送数据的按钮,只有连接建立之后,才将其setEnabled。

    1   tcpClient->disconnectFromHost();
    2   if (tcpClient->state() == QAbstractSocket::UnconnectedState 
    3        || tcpClient->waitForDisconnected(1000))  //已断开连接则进入if{}
    4   {
    5             ui->btnConnect->setText("连接");
    6             ui->btnSend->setEnabled(false);
    7   }

    a)断开TCP连接的函数:void disconnectFromHost()是从QAbstractSocket继承的public function,同时它又是一个virtual function。作用为:Attempts to close the socket. If there is pending data waiting to be written, QAbstractSocket will enter ClosingState and wait until all data has been written. Eventually, it will enter UnconnectedState and emit the disconnected() signal.

    b)等待TCP断开连接函数:bool waitForDisconnected(int msecs = 30000),同样是从QAbstractSocket继承下来的public function,同时它又是一个virtual function。作用为:Waits until the socket has disconnected, up to msecs milliseconds. If the connection has been disconnected, this function returns true; otherwise it returns false. In the case where it returns false, you can call error() to determine the cause of the error.

    3)读取服务器发送过来的数据
    readyRead()是QTcpSocket从父类QIODevice中继承下来的信号:This signal is emitted once every time new data is available for reading from the device’s current read channel。
    readyRead()对应的槽函数为:

    1 void MyTcpClient::ReadData()
    2 {
    3     QByteArray buffer = tcpClient->readAll();
    4     if(!buffer.isEmpty())
    5     {
    6         ui->edtRecv->append(buffer);
    7     }
    8 }

    readAll()是QTcpSocket从QIODevice继承的public function,直接调用就可以读取从服务器发过来的数据了。我这里面把数据显示在textEditor控件上(ui>edtRecv)。由此完成了读操作。

    error(QAbstractSocket::SocketError)是QTcpSocket从QAbstractSocket继承的signal, This signal is emitted after an error occurred. The socketError parameter describes the type of error that occurred.连接到的槽函数定义为:

    1 void MyTcpClient::ReadError(QAbstractSocket::SocketError)
    2 {
    3     tcpClient->disconnectFromHost();
    4     ui->btnConnect->setText(tr("连接"));
    5     QMessageBox msgBox;
    6     msgBox.setText(tr("failed to connect server because %1").arg(tcpClient->errorString()));
    7   8 }

    这段函数的作用是:当错误发生时,首先断开TCP连接,再用QMessageBox提示出errorString,即错误原因。

    4)向服务器发送数据

    1     QString data = ui->edtSend->toPlainText();
    2     if(data != "")
    3     {
    4         tcpClient->write(data.toLatin1()); //qt5去除了.toAscii()
    5     }

    定义一个QString变量,从textEditor(edtSend)中获取带发送数据,write()是QTcpSocket从QIODevice继承的public function,直接调用就可以向服务器发送数据了。这里需要注意的是:toAscii()到qt5就没有了,这里要写成toLatin1()。

    至此,通过4步,我们就完成了TCP Client的程序开发。

    二:服务器端编程
    服务器段编程相比于客户端要繁琐一些,因为对于客户端来说,只能连接一个服务器。而对于服务器来说,它是面向多连接的,如何协调处理多客户端连接就显得尤为重要。
    前言:编程过程中遇到的问题 和 解决的方法
    遇到的问题:每个新加入的客户端,服务器给其分配一个SocketDescriptor后,就会emit newConnection()信号,但分配好的SocketDecriptor并没有通过newConnection()信号传递,所以用户得不到这个客户端标识SocketDescriptor。同样的,每当服务器收到新的消息时,客户端会emit readReady()信号,然而readReady()信号也没有传递SocketDescriptor, 这样的话,服务器端即使接收到消息,也不知道这个消息是从哪个客户端发出的。

    解决的方法:
    1. 通过重写[virtual protected] void QTcpServer::incomingConnection(qintptr socketDescriptor),获取soketDescriptor。自定义TcpClient类继承QTcpSocket,并将获得的soketDescriptor作为类成员。 这个方法的优点是:可以获取到soketDescriptor,灵活性高。缺点是:需要重写函数、自定义类。
    2. 在newConnection()信号对应的槽函数中,通过QTcpSocket *QTcpServer::nextPendingConnection()函数获取 新连接的客户端:Returns the next pending connection as a connected QTcpSocket object. 虽然仍然得不到soketDescriptor,但可以通过QTcpSocket类的peerAddress()和peerPort()成员函数获取客户端的IP和端口号,同样是唯一标识。 优点:无需重写函数和自定义类,代码简洁。缺点:无法获得SocketDecriptor,灵活性差。

    本文介绍第二种方法:

    QT提供了QTcpServer类,可以直接实例化一个客户端,可在help中索引如下:

    1 The QTcpServer class provides a TCP-based server. More...
    2 Header:     #include <QTcpServer> 
    3 qmake:      QT += network
    4 Inherits:       QObject

    从这里,我们可以看到,必须要在.pro文件中添加QT += network才可以进行网络编程,否则是访问不到<QTcpServer>头文件的。

    我们看一下代码头文件:

     1 #ifndef MYTCPSERVER_H
     2 #define MYTCPSERVER_H
     3 
     4 #include <QMainWindow>
     5 #include <QTcpServer>
     6 #include <QTcpSocket>
     7 #include <QNetworkInterface>
     8 #include <QMessageBox>
     9 namespace Ui {
    10 class MyTcpServer;
    11 }
    12 
    13 class MyTcpServer : public QMainWindow
    14 {
    15     Q_OBJECT
    16 
    17 public:
    18     explicit MyTcpServer(QWidget *parent = 0);
    19     ~MyTcpServer();
    20 
    21 private:
    22     Ui::MyTcpServer *ui;
    23     QTcpServer *tcpServer;
    24     QList<QTcpSocket*> tcpClient;
    25     QTcpSocket *currentClient;
    26 
    27 private slots:
    28     void NewConnectionSlot();
    29     void disconnectedSlot();
    30     void ReadData();
    31 
    32     void on_btnConnect_clicked();
    33     void on_btnSend_clicked();
    34     void on_btnClear_clicked();
    35 };
    36 
    37 #endif // MYTCPSERVER_H

    值得注意的是,在服务端编写时,需要同时定义服务器端变量QTcpServer *tcpServer和客户端变量 QList<QTcpSocket*> tcpClient。tcpSocket QList存储了连接到服务器的所有客户端。因为QTcpServer并不是QIODevice的子类,所以在QTcpServer中并没有任何有关读写操作的成员函数,读写数据的操作全权交由QTcpSocket处理。

    1)初始化QTcpServer

    1     tcpServer = new QTcpServer(this);
    2     ui->edtIP->setText(QNetworkInterface().allAddresses().at(1).toString());   //获取本地IP
    3     ui->btnConnect->setEnabled(true);
    4     ui->btnSend->setEnabled(false);
    5 
    6     connect(tcpServer, SIGNAL(newConnection()), this, SLOT(NewConnectionSlot()));

    通过QNetworkInterface().allAddresses().at(1)获取到本机IP显示在lineEditor上(edtIP)。

    介绍如下: [static] QList<QHostAddress> QNetworkInterface::allAddresses() This convenience function returns all IP addresses found on the host machine. It is equivalent to calling addressEntries() on all the objects returned by allInterfaces() to obtain lists of QHostAddress objects then calling QHostAddress::ip() on each of these.: 每当新的客户端连接到服务器时,newConncetion()信号触发,NewConnectionSlot()是用户的槽函数,定义如下:

    1 void MyTcpServer::NewConnectionSlot()
    2 {
    3     currentClient = tcpServer->nextPendingConnection();
    4     tcpClient.append(currentClient);
    5     ui->cbxConnection->addItem(tr("%1:%2").arg(currentClient->peerAddress().toString().split("::ffff:")[1])
    6                                           .arg(currentClient->peerPort()));
    7     connect(currentClient, SIGNAL(readyRead()), this, SLOT(ReadData()));
    8     connect(currentClient, SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));
    9 }

    通过nextPendingConnection()获得连接过来的客户端信息,取到peerAddress和peerPort后显示在comboBox(cbxConnection)上,并将客户端的readyRead()信号连接到服务器端自定义的读数据槽函数ReadData()上。将客户端的disconnected()信号连接到服务器端自定义的槽函数disconnectedSlot()上。

    2)监听端口 与 取消监听

    1      bool ok = tcpServer->listen(QHostAddress::Any, ui->edtPort->text().toInt());
    2      if(ok)
    3      {
    4          ui->btnConnect->setText("断开");
    5          ui->btnSend->setEnabled(true);
    6      }

    a)监听端口的函数:bool QTcpServer::listen(const QHostAddress &*address* = QHostAddress::Any, quint16 *port* = 0),该函数的作用为:Tells the server to listen for incoming connections on address *address* and port *port*. If port is 0, a port is chosen automatically. If address is QHostAddress::Any, the server will listen on all network interfaces. Returns true on success; otherwise returns false.

     1      for(int i=0; i<tcpClient.length(); i++)//断开所有连接
     2      {
     3          tcpClient[i]->disconnectFromHost();
     4          bool ok = tcpClient[i]->waitForDisconnected(1000);
     5          if(!ok)
     6          {
     7              // 处理异常
     8          }
     9          tcpClient.removeAt(i);  //从保存的客户端列表中取去除
    10      }
    11      tcpServer->close();     //不再监听端口

    b)断开客户端与服务器连接的函数:disconnectFromHost()和waitForDisconnected()上文已述。断开连接之后,要将其从QList tcpClient中移除。服务器取消监听的函数:tcpServer->close()。

     1     //由于disconnected信号并未提供SocketDescriptor,所以需要遍历寻找
     2     for(int i=0; i<tcpClient.length(); i++)
     3     {
     4         if(tcpClient[i]->state() == QAbstractSocket::UnconnectedState)
     5         {
     6             // 删除存储在combox中的客户端信息
     7             ui->cbxConnection->removeItem(ui->cbxConnection->findText(tr("%1:%2")
     8                                   .arg(tcpClient[i]->peerAddress().toString().split("::ffff:")[1])
     9                                   .arg(tcpClient[i]->peerPort())));
    10             // 删除存储在tcpClient列表中的客户端信息
    11              tcpClient[i]->destroyed();
    12              tcpClient.removeAt(i);
    13         }
    14     }

    c)若某个客户端断开了其与服务器的连接,disconnected()信号被触发,但并未传递参数。所以用户需要遍历tcpClient list来查询每个tcpClient的state(),若是未连接状态(UnconnectedState),则删除combox中的该客户端,删除tcpClient列表中的该客户端,并destroy()。

    3)读取客户端发送过来的数据

     1     // 客户端数据可读信号,对应的读数据槽函数
     2     void MyTcpServer::ReadData()
     3     {
     4         // 由于readyRead信号并未提供SocketDecriptor,所以需要遍历所有客户端
     5         for(int i=0; i<tcpClient.length(); i++)
     6         {
     7             QByteArray buffer = tcpClient[i]->readAll();
     8             if(buffer.isEmpty())    continue;
     9 
    10             static QString IP_Port, IP_Port_Pre;
    11             IP_Port = tr("[%1:%2]:").arg(tcpClient[i]->peerAddress().toString().split("::ffff:")[1])
    12                                          .arg(tcpClient[i]->peerPort());
    13 
    14             // 若此次消息的地址与上次不同,则需显示此次消息的客户端地址
    15             if(IP_Port != IP_Port_Pre)
    16                 ui->edtRecv->append(IP_Port);
    17 
    18             ui->edtRecv->append(buffer);
    19 
    20             //更新ip_port
    21             IP_Port_Pre = IP_Port;
    22         }
    23     }

    这里需要注意的是,虽然tcpClient产生了readReady()信号,但readReady()信号并没有传递任何参数,当面向多连接客户端时,tcpServer并不知道是哪一个tcpClient是数据源,所以这里遍历tcpClient列表来读取数据(略耗时,上述的解决方法1则不必如此)。 读操作由tcpClient变量处理:tcpClient[i]->readAll();

    4)向客户端发送数据

    1     //全部连接
    2     if(ui->cbxConnection->currentIndex() == 0)
    3     {
    4         for(int i=0; i<tcpClient.length(); i++)
    5             tcpClient[i]->write(data.toLatin1()); //qt5除去了.toAscii()
    6     }

    a)向当前连接的所有客户端发数据,遍历即可。

     1     //指定连接
     2     QString clientIP = ui->cbxConnection->currentText().split(":")[0];
     3     int clientPort = ui->cbxConnection->currentText().split(":")[1].toInt();
     4     for(int i=0; i<tcpClient.length(); i++)
     5     {
     6         if(tcpClient[i]->peerAddress().toString().split("::ffff:")[1]==clientIP
     7                         && tcpClient[i]->peerPort()==clientPort)
     8         {
     9             tcpClient[i]->write(data.toLatin1());
    10             return; //ip:port唯一,无需继续检索
    11         }
    12     }

    b)在comboBox(cbxConnction)中选择指定连接发送数据:通过peerAddress和peerPort匹配客户端,并发送。写操作由tcpClient变量处理:tcpClient[i]->write()。

    至此,通过4步,我们就完成了TCP Server的程序开发

  • 相关阅读:
    3.8快乐
    只剩一个人了
    需求分析
    再也不看皇马比赛
    最近蛮忙,没头绪
    ↗☻【响应式Web设计 HTML5和CSS3实战 #BOOK#】第5章 CSS3:选择器、字体和颜色模式
    ↗☻【高性能网站建设进阶指南 #BOOK#】第12章 尽早刷新文档的输出
    ↗☻【响应式Web设计 HTML5和CSS3实战 #BOOK#】第4章 响应设计中的HTML5
    ↗☻【JavaScript】code
    ↗☻【高性能网站建设进阶指南 #BOOK#】第11章 划分主域
  • 原文地址:https://www.cnblogs.com/ybqjymy/p/13683658.html
Copyright © 2011-2022 走看看