1 Star 1 Fork 1

Atom / Qt_hmi

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
command.cpp 2.53 KB
一键复制 编辑 原始数据 按行查看 历史
Atom 提交于 2021-01-20 19:52 . Fist upload source code
#include "command.h"
#include <QAbstractSocket>
#include <QTcpSocket>
#include <QDebug>
#include <QHostAddress>
#define TIME_OUT 500
#define MAX_READ_BUFFER_SIZE 100000
Command::Command()
{
}
Command::~Command()
{
}
bool CommandSock::isConnAlive()
{
return !(opClient == NULL);
}
void CommandSock::slotConnectOperateServer(const char *ipaddr, int port)
{
opClient = new QTcpSocket();
connect(opClient, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(slotStateChanged(QAbstractSocket::SocketState)));
opClient->connectToHost(ipaddr, port);
if (!opClient->waitForConnected(TIME_OUT * 5)) {//wait 2500ms
slotConnectError(opClient->error());
this->slotDisconnectOperateServer();
return;
}
qDebug() << "Connected to " << opClient->peerAddress().toString() << ":" << opClient->peerPort() << "sta: " << QString("%1").arg(opClient->state());
}
void CommandSock::slotSendOperateData(QByteArray &data)
{
opClient->write(data);
opClient->waitForBytesWritten(TIME_OUT * 2);
opClient->flush();
}
void CommandSock::slotDisconnectOperateServer(void)
{
if (!opClient)
return;
//disconnect(opClient, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotConnectError(QAbstractSocket::SocketError)));
opClient->close();
opClient->deleteLater();
opClient = NULL;
}
void CommandSock::slotReceiveData(QByteArray*data, unsigned int mSec)
{
opClient->waitForReadyRead(mSec);
(*data) = opClient->readAll();
}
void CommandSock::slotConnectError(QAbstractSocket::SocketError err)
{
qDebug() << "CommandSock connection error occured" << err;
switch (err)
{
case QAbstractSocket::ConnectionRefusedError:
qDebug() << "Connecting refused";
emit error("Connecting refused by server, retrying ()...");
break;
case QAbstractSocket::RemoteHostClosedError:
qDebug() << "Server closed the connection !";
emit error("Server closed the connection !");
break;
case QAbstractSocket::HostNotFoundError:
qDebug() << "Server not found";
emit error (QString ("Server not found, host name:"));
break;
default:
qDebug() << "Connection to server is broken";
emit error("Connection to server is broken !");
break;
}
}
void CommandSock::slotStateChanged(QAbstractSocket::SocketState newSta)
{
qDebug() << "Socket state: " << newSta;
if (newSta == QAbstractSocket::ClosingState || newSta == QAbstractSocket::UnconnectedState) {
emit error("Close");
}
}
C++
1
https://gitee.com/atom-zh/qt_hmi.git
git@gitee.com:atom-zh/qt_hmi.git
atom-zh
qt_hmi
Qt_hmi
master

搜索帮助