QT socket TCP通信程序模板--客户端

服务器端的操作是,建立server,然后进入listen监听状态,等待客户端发起连接。

客户端的编程更为简单:

(1)建立tcp socket

(2)把QTcpSocket的3个关键的信号槽connect起来,3个信号如下:

(3)把客户端QTcpSocke对象绑定(bind)与本机端口绑定。当然,也可以不绑定,操作系统会帮我们随机绑定一个可用端口。

(4)向服务器发起连接请求:
void QAbstractSocket::connectToHost(const QString &hostName, quint16 port, OpenMode openMode = ReadWrite, NetworkLayerProtocol protocol = AnyIPProtocol)
总共4个形参,前2个比较重要,第一个是服务器的IP,第二个是服务器的端口号。

一旦该函数成功执行,就会触发QTcpSocket::connected()信号。

(5)发送数据,用QTcpSocket::write(const char *data, qint64 maxSize)

(6)接收数据,在readyRead()的槽里进行,读出的函数是:
QByteArray QTcpSocket::readAll()

示例程序:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QMap>
#include <QByteArray>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_ptnLink_clicked();
    void when_tcpConnected(void);
    void when_tcpDisConnected(void);
    void when_tcpReceivedData(void);
    void on_ptnSend_clicked();

private:
    Ui::MainWindow *ui;
    QTcpSocket *tcpSkt;
};

#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"

#define debug_print(str) ui->textEditDebug->append(str)


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    tcpSkt = new QTcpSocket();
    connect(tcpSkt, SIGNAL(connected()), this, SLOT(when_tcpConnected()));//与TCP服务器连接成功
    connect(tcpSkt, SIGNAL(disconnected()), this, SLOT(when_tcpDisConnected()));//tcp掉线
    connect(tcpSkt, SIGNAL(readyRead()), this, SLOT(when_tcpReceivedData()));//tcp客户端接收到了数据
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_ptnLink_clicked()
{
    QHostAddress serverIp;
    if(!serverIp.setAddress(ui->lineEditServerIP->text()))
       debug_print("你输入的服务器IP有误");

    tcpSkt->close();
    tcpSkt->connectToHost(serverIp, ui->spinPort->value());
}

void MainWindow::when_tcpConnected()
{
    debug_print("已连接到TCP服务器");
}

void MainWindow::when_tcpDisConnected()
{
    debug_print("与TCP服务器的连接已断开");
}

void MainWindow::when_tcpReceivedData()
{
    QByteArray ba;
    ba = tcpSkt->readAll();
    debug_print(QString(ba));
}

void MainWindow::on_ptnSend_clicked()
{

    char*  ch;
    QByteArray ba = ui->lineEditSend->text().toLatin1(); // must
    ch=ba.data();

    tcpSkt->write(ch, ba.size());
}

 

为了测试上述程序,用到了网络调试助手SSCOM,

把sscom设置成TCP服务器模式,并进入监听状态。然后点击我的软件的【发起连接申请按钮】,在窗口就会看到”已连接到TCP服务器“。点击SSCOM中的断开按钮,在我的软件中会看到”与TCP服务器的连接已断开“的提示。

我的软件与SSCOM互相收发数据,经测试也没问题。

SSCOM的设置以及测试画面如下:

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章