เพื่อให้เราไม่พลาดการสื่อสาร จำเป็นต้องใช้ signal and slot
========================================
============== signalSocket.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
HEADERS += \
sockettest.h
target.path = /home/pi/Pump
INSTALLS += target
========================================
================ main.cpp =================
========================================#include <QCoreApplication>
#include <sockettest.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
SocketTest mTest;
mTest.Test();
return a.exec();
}
========================================
=============== sockettest.h =================
========================================#ifndef SOCKETTEST_H
#define SOCKETTEST_H
#include <QObject>
#include <QDebug>
#include <QTcpSocket>
#include <QAbstractSocket>
class SocketTest : public QObject
{
Q_OBJECT
public:
explicit SocketTest(QObject *parent = nullptr);
void Test();
signals:
public slots:
void connected();
void disconnected();
void bytesWritten (qint64 bytes);
void readyRead();
private:
QTcpSocket *socket;
};
#endif // SOCKETTEST_H
========================================
============== sockettest.cpp =================
========================================
#include "sockettest.h"
SocketTest::SocketTest(QObject *parent) : QObject(parent)
{
}
void SocketTest::Test(){
socket = new QTcpSocket(this);
connect(socket,SIGNAL(connected()),this,SLOT(connected()));
connect(socket,SIGNAL(disconnected()),this,SLOT(disconnected()));
connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()));
connect(socket,SIGNAL(bytesWritten(qint64)),this,SLOT(bytesWritten(qint64)));
qDebug() << "Connecting...";
//socket->connectToHost("voidrealms.com",80);
socket->connectToHost("10.0.0.227",1234);
if(!socket->waitForConnected(1000)){
qDebug() << "Error " << socket->errorString();
}
}
void SocketTest::connected()
{
qDebug() << "Connected";
}
void SocketTest::disconnected()
{
qDebug() << "Disconnected";
socket->close();
}
void SocketTest::bytesWritten (qint64 bytes)
{
qDebug() << "we wrote: " << bytes;
}
void SocketTest::readyRead()
{
qDebug() << "Reading...";
qDebug() << socket->readAll();
}
ที่มา
https://www.youtube.com/watch?v=j9uAfTAZrdM
ไม่มีความคิดเห็น:
แสดงความคิดเห็น