วันอังคารที่ 18 กันยายน พ.ศ. 2561

tcp client

==================================
========== test_network_client.pro  ========
==================================
QT -= gui
QT += network

CONFIG += c++11 console
CONFIG -= app_bundle

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += main.cpp \
    sockettest.cpp

target.path = /home/pi/Pump
INSTALLS += target

HEADERS += \
    sockettest.h


==================================
==============  main.cpp  ============
==================================
#include <QCoreApplication>
#include "sockettest.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    SocketTest cTest;
    cTest.Connect();

    return a.exec();
}

==================================
============  sockettest.h  ============
==================================
#ifndef SOCKETTEST_H
#define SOCKETTEST_H

#include <QObject>
#include <QTcpSocket>
#include <QDebug>


class SocketTest : public QObject
{
    Q_OBJECT
public:
    explicit SocketTest(QObject *parent = nullptr);
    void Connect();

signals:

public slots:

private:
    QTcpSocket *socket;
};

#endif // SOCKETTEST_H


==================================
============  sockettest.cpp  ============
==================================
#include "sockettest.h"

SocketTest::SocketTest(QObject *parent) : QObject(parent)
{

}

void SocketTest::Connect(){
    socket = new QTcpSocket(this);

    socket->connectToHost("10.0.0.227", 1234);
    if(socket->waitForConnected(3000)){
        qDebug() << "Connected";
        socket->write("hello server\r\n\r\n");
        socket->waitForBytesWritten(1000);
        socket->waitForReadyRead(3000);
        qDebug() << "Reading" << socket->bytesAvailable();
        qDebug() << socket->readAll();
        socket->close();
    }
    else{
        qDebug() << "Not connected.";
    }
}

ที่มา
https://www.youtube.com/watch?v=u5OdR46542M

ไม่มีความคิดเห็น: