#include <QtGui/QApplication>#include "wgtmain.h"#include "thread.h"int main(int argc, char *argv[]){ QApplication a(argc, argv); wgtMain w; w.show(); Thread th; th.start(); return a.exec();}
#ifndef THREAD_H#define THREAD_H#include <QThread>#include <QtNetwork/QTcpSocket>class Thread : public QThread{ Q_OBJECT QTcpSocket * sock;public: explicit Thread(QObject *parent = 0);protected: void run();};#endif // THREAD_H
#include "thread.h"Thread::Thread(QObject *parent) : QThread(parent){ this->sock = new QTcpSocket(this); this->sock->connectToHost("127.0.0.1", 1234);}void Thread::run(){ while(true) { QByteArray array = this->sock->readAll(); if(array.length() > 0) { if(array.data() == "somedata") this->sock->write("somedata_to_send"); } }}
#ifndef WGTMAIN_H#define WGTMAIN_H#include <QWidget>#include <QTcpSocket>namespace Ui { class wgtMain;}class wgtMain : public QWidget{ Q_OBJECTpublic: explicit wgtMain(QWidget *parent = 0); ~wgtMain();private slots: void on_pushButton_clicked();private: Ui::wgtMain *ui;};#endif // WGTMAIN_H
#include "wgtmain.h"#include "ui_wgtmain.h"wgtMain::wgtMain(QWidget *parent) : QWidget(parent), ui(new Ui::wgtMain){ ui->setupUi(this);}wgtMain::~wgtMain(){ delete ui;}void wgtMain::on_pushButton_clicked(){ QTcpSocket sock (this); sock.connectToHost("127.0.0.1", 1234); sock.write("some_data_to_sent_from_slot"); sock.disconnectFromHost();}
C++ (Qt)this->sock = new QTcpSocket(this);
C++ (Qt)class MySocket : public QTcpSocket{ Q_OBJECTpublic: MySocket(QObject *parent = 0) : QTcpSocket(parent) { connect(this, SIGNAL(readyRead()), this, SLOT(slotTransaction())); }private slots: void slotTransaction() { QByteArray array = readAll(); if(array.length() > 0) { if(array.data() == "somedata") write("somedata_to_send"); } }} ...... void Thread::run(){ MySocket sock; sock.connectToHost("127.0.0.1", 1234); exec(); sock.disconnectFromHost();}
this->sock = new QTcpSocket(this);
C++ (Qt)volatile