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

tcp server

พอดีมีงานที่ต้องใช้งาน TCP/IP ก็เลยต้องมาเรียนรู้กันสักหน่อย


================================
========= test_network_server.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 \
    myserver.cpp

HEADERS += \
    myserver.h

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


================================
===========  main.cpp  ==============
================================
#include <QCoreApplication>
#include <myserver.h>

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

    myServer mServer;

    return a.exec();
}


================================
===========  myserver.h  ============
================================#ifndef MYSERVER_H
#define MYSERVER_H

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

class myServer : public QObject
{
    Q_OBJECT
public:
    explicit myServer(QObject *parent = nullptr);

signals:


public slots:
    void newConnection();

private:
    QTcpServer *server;
};

#endif // MYSERVER_H


================================
===========  myserver.cpp  ===========
================================
#include "myserver.h"

myServer::myServer(QObject *parent) : QObject(parent)
{
    server = new QTcpServer(this);
    connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));
    if(!server->listen(QHostAddress::Any,1234)){
        qDebug()<<"Server could not start";
    }
    else{
        qDebug()<<"Server started";
    }
}

void myServer::newConnection(){
    QTcpSocket *socket = server->nextPendingConnection();
    socket->write("hello client\r\n");
    socket->flush();
    socket->waitForBytesWritten(3000);

    socket->close();
}

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

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