Qt实现telnet服务记录

Posted 林夕07

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt实现telnet服务记录相关的知识,希望对你有一定的参考价值。

最近在做关于FlightGear的一个指令控制的研究,由于每次都需要手动从cmd跳到telnet中,所以实现拿Qt实现一个telnet功能的小模块。

目录

FlightGear(开源)

FlightGear是一款开源飞行模拟器。项目始于1997年,主要目标是为学术科研领域创造一个尖端的飞行模拟器框架,也可拓展到飞行训练,飞行仿真,模拟飞行游戏等方面。
它支持全球三维实景,20,000多个跑道、400多种飞行器、跨平台、多人联飞、多样的开放飞行数据模型等功能。重点这是开源的。

源码

项目结构

Pro配置文件

在*.pro文件中需要添加

QT       +=  network
win32

    LIBS     +=-lws2_32

mainWindow类

mainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "qttelnet.h"
namespace Ui 
class MainWindow;


class MainWindow : public QMainWindow

    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    QtTelnet * telnet ;
private:
    Ui::MainWindow *ui;

private slots:
    void telnetMessage(const QString &);
    void telnetLoginRequired(); //
    void telnetLoginFailed();  // 登录失败
    void telnetLoggedOut();  // 退出成功
    void telnetLoggedIn();  // 登录成功
    void telnetConnectionError(QAbstractSocket::SocketError);  // 连接错误
    void on_pb_Link_clicked();
    void on_pb_close_clicked();
    void on_pb_Send_clicked();
;

#endif // MAINWINDOW_H

mainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)

    ui->setupUi(this);
    telnet = new QtTelnet(this);

    connect(telnet, SIGNAL(message(const QString &)),this, SLOT(telnetMessage(const QString &)));
    connect(telnet, SIGNAL(loginRequired()),this, SLOT(telnetLoginRequired()));
    connect(telnet, SIGNAL(loginFailed()),this, SLOT(telnetLoginFailed()));
    connect(telnet, SIGNAL(loggedOut()),this, SLOT(telnetLoggedOut()));
    connect(telnet, SIGNAL(loggedIn()),this, SLOT(telnetLoggedIn()));
    connect(telnet, SIGNAL(connectionError(QAbstractSocket::SocketError)),
            this, SLOT(telnetConnectionError(QAbstractSocket::SocketError)));



MainWindow::~MainWindow()

    delete ui;


void MainWindow::telnetMessage(const QString &msg)

    ui->te_Msg->append(msg);


void MainWindow::telnetLoginRequired()

    QString user = ui->le_User->text();
    QString passwd  = ui->le_Passwd->text();

    if(user == "" || passwd == "")
    
        ui->te_Msg->append("用户名和密码不能为空!");
        return;
    
    telnet->login(user,passwd); // 登入telnet
    // telnet->logout(); // 登出


void MainWindow::telnetLoginFailed()

    ui->te_Msg->append("登录失败!");


void MainWindow::telnetLoggedOut()

    ui->te_Msg->append("登出成功!");


void MainWindow::telnetLoggedIn()

    ui->te_Msg->append("登录成功!");


void MainWindow::telnetConnectionError(QAbstractSocket::SocketError error)

    ui->te_Msg->append(QString("连接错误: %1").arg(error));


void MainWindow::on_pb_Link_clicked()

    QString host = ui->le_Host->text();
    if(host == "")
    
        ui->te_Msg->append("IP地址不能为空!");
        return ;
    
    telnet->connectToHost(host);




void MainWindow::on_pb_close_clicked()

    telnet->close();


void MainWindow::on_pb_Send_clicked()

    QString cmd = ui->le_SendText->text() + "\\r\\n" ;
    telnet->sendData(cmd);


mainWindow.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>713</width>
    <height>483</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Telnet客户端</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <layout class="QGridLayout" name="gridLayout">
    <item row="0" column="0">
     <widget class="QLabel" name="label">
      <property name="text">
       <string>IP地址:</string>
      </property>
     </widget>
    </item>
    <item row="0" column="1">
     <widget class="QLineEdit" name="le_Host"/>
    </item>
    <item row="0" column="2">
     <widget class="QLabel" name="label_2">
      <property name="text">
       <string>用户名:</string>
      </property>
     </widget>
    </item>
    <item row="0" column="3">
     <widget class="QLineEdit" name="le_User"/>
    </item>
    <item row="0" column="4">
     <widget class="QLabel" name="label_3">
      <property name="text">
       <string>密码:</string>
      </property>
     </widget>
    </item>
    <item row="0" column="5">
     <widget class="QLineEdit" name="le_Passwd"/>
    </item>
    <item row="0" column="6">
     <widget class="QPushButton" name="pb_Link">
      <property name="text">
       <string>连接</string>
      </property>
     </widget>
    </item>
    <item row="0" column="7">
     <widget class="QPushButton" name="pb_close">
      <property name="text">
       <string>断开</string>
      </property>
     </widget>
    </item>
    <item row="1" column="0" colspan="8">
     <widget class="QTextEdit" name="te_Msg"/>
    </item>
    <item row="2" column="7">
     <widget class="QPushButton" name="pb_Send">
      <property name="text">
       <string>发送</string>
      </property>
     </widget>
    </item>
    <item row="2" column="0" colspan="7">
     <widget class="QLineEdit" name="le_SendText"/>
    </item>
   </layout>
  </widget>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

qttelnet类

qttelnet.h

/****************************************************************************
**
** This file is part of a Qt Solutions component.
** 
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** 
** Contact:  Qt Software Information (qt-info@nokia.com)
** 
** Commercial Usage  
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia.
** 
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
** 
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
** 
** GNU General Public License Usage 
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
** 
** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third
** Party Software they are using.
** 
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** 
****************************************************************************/

#ifndef QTTELNET_H
#define QTTELNET_H

#include <QtCore/QObject>
#include <QtCore/QString>
#include <QtCore/QSize>
#include <QtCore/QRegExp>
#include <QtNetwork/QTcpSocket>
#include <QByteArray>

class QtTelnetPrivate;

#if defined(Q_WS_WIN)
#  if !defined(QT_QTTELNET_EXPORT) && !defined(QT_QTTELNET_IMPORT)
#    define QT_QTTELNET_EXPORT
#  elif defined(QT_QTTELNET_IMPORT)
#    if defined(QT_QTTELNET_EXPORT)
#      undef QT_QTTELNET_EXPORT
#    endif
#    define QT_QTTELNET_EXPORT __declspec(dllimport)
#  elif defined(QT_QTTELNET_EXPORT)
#    undef QT_QTTELNET_EXPORT
#    define QT_QTTELNET_EXPORT __declspec(dllexport)
#  endif
#else
#  define QT_QTTELNET_EXPORT
#endif

class QT_QTTELNET_EXPORT QtTelnet : public QObject

    Q_OBJECT
    friend class QtTelnetPrivate;
public:
    QtTelnet(QObject *parent = 0);
    ~QtTelnet();

    enum Control  GoAhead, InterruptProcess, AreYouThere, AbortOutput,
                   EraseCharacter, EraseLine, Break, EndOfFile, Suspend,
                   Abort ;

    void connectToHost(const QString &host, quint16 port = 23);

    void login(const QString &user, const QString &pass);

    void setWindowSize(const QSize &size);
    void setWindowSize(int width, int height); // In number of characters
    QSize windowSize() const;
    bool isValidWindowSize() const;

    void setSocket(QTcpSocket *socket);
    QTcpSocket *socket() const;

    void setPromptPattern(const QRegExp &pattern);
    void setPromptString(const QString &pattern)
     setPromptPattern(QRegExp(QRegExp::escape(pattern))); 
public Q_SLOTS:
    void close();
    void logout();
    void sendControl(Control ctrl);
    void sendData(const QString &data);
    void sendSync();

Q_SIGNALS:
    void loginRequired();
    void loginFailed();
    void loggedIn();
    void loggedOut();
    void connectionError(QAbstractSocket::SocketError error);
    void message(const QString &data);

public:
    void setLoginPattern(const QRegExp &pattern);
    void setLoginString(const QString &pattern)
     setLoginPattern(QRegExp(QRegExp::escape(pattern))); 
    void setPasswordPattern(const QRegExp &pattern);
    void setPasswordString(const QString &pattern)
     setPasswordPattern(QRegExp(QRegExp::escape(pattern))); 

private:
    QtTelnetPrivate *d;
;
#endif

qttelnet.cpp

/****************************************************************************
**
** This file is part of a Qt Solutions component.
** 
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** 
** Contact:  Qt Software Information (qt-info@nokia.com)
** 
** Commercial Usage  
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia.
** 
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
** 
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
** 
** GNU General Public License Usage 
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
** 
** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third
** Party Software they are using.
** 
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** 
****************************************************************************/

/*!
    \\class QtTelnet
    \\brief The QtTelnet class proveds an API to connect to Telnet servers,
    issue commands and receive replies.

    When a QtTelnet object has been created, you need to call
    connectToHost() to establish a connection with a Telnet server.
    When the connection is established the connected() signal is
    emitted. At this point you should call login(). The
    QtTelnet object will emit connectionError() if the connection
    fails, and authenticationFailed() if the login() failed.

    Once the connection has been successfully established and
    you've logged in you can send control messages using sendControl()
    and data using sendData(). Connect to the message() signal to
    receive data from the Telnet server. The connection is closed with
    close().

    You can use your own socket if you call setSocket() before
    connecting. The socket used by QtTelnet is available from
    socket().
*/

#include "qttelnet.h"
#include <QtNetwork/QTcpSocket>
#include <QtCore/QList>
#include <QtCore/QMap>
#include <QtCore/QPair>
#include <QtCore/QVariant>
#include <QtCore/QSocketNotifier>
Python - Qt。如何为 Telnet 或 ssh 服务器交互制作终端窗口

如何在 telnet 客户端上实现命令历史记录? (上/下箭头)

2014.8.27 CAD数据结构

Qt 框架 开发HTTP 服务器 开发记录

新型基础测绘与实景三维中国建设技术文件基础地理实体数据元数据

新型基础测绘与实景三维中国建设技术文件基础地理实体数据元数据