From 9a6a17caffb679f58ddc48976819c8f3f625f601 Mon Sep 17 00:00:00 2001
From: touwoyimuli <touwoyimuli@gmail.com>
Date: Fri, 22 Nov 2019 22:59:36 +0800
Subject: [PATCH] =?UTF-8?q?feat:=20EcTcpServer=20=E5=8A=9F=E8=83=BD?=
 =?UTF-8?q?=E5=AE=8C=E6=88=90?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 QtTcpEx/ExTcpServer/ExTcpServer.cpp | 112 ++++++++++++++++++++++------
 QtTcpEx/ExTcpServer/ExTcpServer.h   |   6 +-
 QtTcpEx/ExTcpServer/ExTcpServer.ui  |  10 +--
 3 files changed, 91 insertions(+), 37 deletions(-)

diff --git a/QtTcpEx/ExTcpServer/ExTcpServer.cpp b/QtTcpEx/ExTcpServer/ExTcpServer.cpp
index 4c0a2f1..f5f8fc6 100644
--- a/QtTcpEx/ExTcpServer/ExTcpServer.cpp
+++ b/QtTcpEx/ExTcpServer/ExTcpServer.cpp
@@ -6,6 +6,20 @@ ExTcpServer::ExTcpServer(QWidget *parent) :
     ui(new Ui::ExTcpServer)
 {
     ui->setupUi(this);
+
+    m_labListen = new QLabel("监听状态:");
+    m_labSocket = new QLabel("socket状态:");
+    m_labListen->setMidLineWidth(200);
+    m_labSocket->setMinimumWidth(200);
+    ui->statusBar->addWidget(m_labListen);
+    ui->statusBar->addWidget(m_labSocket);
+
+    QString localeIp = getLocalIp();
+    setWindowTitle(windowTitle() + "---IP地址:" + localeIp);
+    ui->comboBox->addItem(localeIp);
+
+    m_tcpServer = new QTcpServer(this);
+    connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
 }
 
 ExTcpServer::~ExTcpServer()
@@ -13,6 +27,27 @@ ExTcpServer::~ExTcpServer()
     delete ui;
 }
 
+QString ExTcpServer::getLocalIp()
+{
+    QString hostName = QHostInfo::localHostName();
+    QHostInfo hostInfo = QHostInfo::fromName(hostName);
+    QString locaIp;
+
+    QList<QHostAddress> list = hostInfo.addresses();
+
+    if (list.empty())
+        return "null QString";
+
+    foreach (QHostAddress addr, list) {
+        if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
+            locaIp = addr.toString();
+            break;
+        }
+    }
+
+    return locaIp;
+}
+
 void ExTcpServer::closeEvent(QCloseEvent *event)   //关闭窗口时候停止监听
 {
     if (m_tcpServer->isListening())
@@ -60,37 +95,23 @@ void ExTcpServer::on_actQuit_triggered()
 
 void ExTcpServer::on_btnSend_clicked()
 {
+    QString msg = ui->lineEdit->text();
+    ui->plainTextEdit->appendPlainText("[out]" + msg);
+    ui->lineEdit->clear();
+    ui->plainTextEdit->hasFocus();
 
+    QByteArray str = msg.toUtf8();
+    str.append('\n');
+    m_tcpSocket->write(str);
 }
 
-
-
-void ExTcpServer::on_actHostInfo_triggered()
+void ExTcpServer::onSocketReadyRead()     //读取缓冲区行文本
 {
-    QString hostName = QHostInfo::localHostName();
-    QHostInfo hostInfo = QHostInfo::fromName(hostName);
-    ui->plainTextEdit->appendPlainText("本机主机名:" + hostName);
-
-    QList<QHostAddress> list = hostInfo.addresses();
-
-    if (list.empty())
-        return;
-
-    foreach (QHostAddress addr, list) {
-        if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
-            ui->plainTextEdit->appendPlainText("本机 IP 地址:" + addr.toString());
-
-            if (ui->comboBox->findText(addr.toString()) < 0)  //下拉列表没有的就添加进去
-                ui->comboBox->addItem(addr.toString());
-        }
+    while (m_tcpSocket->canReadLine()) {
+        ui->plainTextEdit->appendPlainText("[in]" + m_tcpSocket->readLine());
     }
 }
 
-void ExTcpServer::onSocketReadyRead()
-{
-
-}
-
 void ExTcpServer::onClientConnected()    //客户端连接时
 {
     ui->plainTextEdit->appendPlainText("客户端套接字连接\n对等(peer)地址:" + m_tcpSocket->peerAddress().toString()
@@ -103,3 +124,46 @@ void ExTcpServer::onClientDisonnected()  //客户端断开连接时
     ui->plainTextEdit->appendPlainText("客户端套接字断开");
     m_tcpSocket->deleteLater();
 }
+
+void ExTcpServer::onNewConnection()
+{
+    m_tcpSocket = m_tcpServer->nextPendingConnection();   //创建 socket
+
+    connect(m_tcpSocket, SIGNAL(connected()), this, SLOT(onClientConnected()));
+    onClientConnected();   //本函数有写
+    connect(m_tcpSocket, SIGNAL(disconnected()), this, SLOT(onClientDisonnected()));
+    connect(m_tcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
+    onSocketStateChange(m_tcpSocket->state());  //本函数也有写  后面尝试删除此两行, 看看或不会有异常
+    connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(onSocketReadyRead()));
+}
+
+void ExTcpServer::onSocketStateChange(QAbstractSocket::SocketState socketState)
+{
+    switch (socketState) {
+    case QAbstractSocket::UnconnectedState:
+        m_labSocket->setText("socket状态:UnconnectedState");
+        break;
+    case QAbstractSocket::HostLookupState:
+        m_labSocket->setText("socket状态:HostLookupState");
+        break;
+    case QAbstractSocket::ConnectingState:
+        m_labSocket->setText("socket状态:ConnectingState");
+        break;
+    case QAbstractSocket::ConnectedState:
+        m_labSocket->setText("socket状态:ConnectedState");
+        break;
+    case QAbstractSocket::BoundState:
+        m_labSocket->setText("socket状态:BoundState");
+        break;
+    case QAbstractSocket::ClosingState:
+        m_labSocket->setText("socket状态:ClosingState");
+        break;
+    case QAbstractSocket::ListeningState:
+        m_labSocket->setText("socket状态:ListeningState");
+        break;
+    default:
+        m_labSocket->setText("socket状态:其他未知状态...");
+        break;
+    }
+}
+
diff --git a/QtTcpEx/ExTcpServer/ExTcpServer.h b/QtTcpEx/ExTcpServer/ExTcpServer.h
index 4823edb..20835c4 100644
--- a/QtTcpEx/ExTcpServer/ExTcpServer.h
+++ b/QtTcpEx/ExTcpServer/ExTcpServer.h
@@ -25,8 +25,6 @@ private:
 protected:
     void closeEvent(QCloseEvent* event);
 
-
-
 private slots:
 //UI的槽函数
     void on_actStart_triggered();      //开始监听
@@ -34,13 +32,13 @@ private slots:
     void on_actClear_triggered();      //清除文本框内容
     void on_actQuit_triggered();       //退出程序
     void on_btnSend_clicked();         //发送消息
-    void on_actHostInfo_triggered();   //获取本机的 name 和 IP
 
 //自定义的槽函数
     void onSocketReadyRead();          //读取 socket 传入时候的数据
     void onClientConnected();          //client socket conneted
     void onClientDisonnected();        //client socket disconneted
-
+    void onNewConnection();            //QTcpServer 的 newConnect() 信号
+    void onSocketStateChange(QAbstractSocket::SocketState socketState);
 
 private:
     Ui::ExTcpServer *ui;
diff --git a/QtTcpEx/ExTcpServer/ExTcpServer.ui b/QtTcpEx/ExTcpServer/ExTcpServer.ui
index c8d538a..477308e 100644
--- a/QtTcpEx/ExTcpServer/ExTcpServer.ui
+++ b/QtTcpEx/ExTcpServer/ExTcpServer.ui
@@ -81,7 +81,7 @@
        <widget class="QLineEdit" name="lineEdit"/>
       </item>
       <item>
-       <widget class="QPushButton" name="btnSenf">
+       <widget class="QPushButton" name="btnSend">
         <property name="text">
          <string>发送</string>
         </property>
@@ -165,14 +165,6 @@
     <string>退出程序</string>
    </property>
   </action>
-  <action name="actHostInfo">
-   <property name="text">
-    <string>本机地址</string>
-   </property>
-   <property name="toolTip">
-    <string>获取本机地址</string>
-   </property>
-  </action>
  </widget>
  <layoutdefault spacing="6" margin="11"/>
  <resources>