proto-debuger/protoDebuger/network_controller.cpp

93 lines
2.3 KiB
C++
Raw Normal View History

2021-04-24 17:21:31 +00:00
#include "network_controller.h"
2021-04-29 14:26:45 +00:00
NetworkController::NetworkController(NetworkController::NetWorkType type, QString ip, uint16_t port)
2021-04-24 17:21:31 +00:00
{
2021-05-02 18:02:25 +00:00
mType = type;
if(_checkType(type) == TYPE_UNKOWN){
}
2021-04-24 17:21:31 +00:00
if(type == NetWorkType::TYPE_TCP_CLIENT){
mTcp = new QTcpSocket();
mCnn = mTcp;
QObject::connect(mTcp, SIGNAL(readyRead()), this, SLOT(on_ready_read()));
QObject::connect(mTcp, SIGNAL(disconnected()), this, SLOT(on_disconect()));
mTcp->connectToHost(ip,port,QIODevice::ReadWrite);
}
2021-05-02 18:02:25 +00:00
if(type == NetWorkType::TYPE_TCP_SERVER){
mTcpServer = new QTcpServer();
connect(mTcpServer,SIGNAL(newConnection()),
this,SLOT(on_server_accept()));
connect(mTcpServer, SIGNAL(acceptError(QAbstractSocket::SocketError socketError)),
this, SLOT(displayError()));
if (!mTcpServer->listen(QHostAddress::Any, port))
{
qDebug() << "m_pTcpServer->listen() error";
}
}
2021-04-24 17:21:31 +00:00
}
2021-04-29 14:26:45 +00:00
int NetworkController::SendData(int8_t *data, uint32_t len)
{
2021-05-01 15:41:40 +00:00
if(nullptr == data)
return -1;
return mCnn->write((const char *)data,len);
2021-04-29 14:26:45 +00:00
}
2021-05-01 15:41:40 +00:00
int NetworkController::ReadData(int8_t *data)
2021-04-24 17:21:31 +00:00
{
2021-05-01 15:41:40 +00:00
if(nullptr != data){
return -1;
}
memcpy(data,mCnn->readAll().data(),mCnn->size());
}
2021-04-24 17:21:31 +00:00
2021-05-01 15:41:40 +00:00
NetworkController::~NetworkController()
{
delete mTcp;
2021-04-24 17:21:31 +00:00
}
2021-04-29 14:26:45 +00:00
void NetworkController::on_ready_read()
2021-04-24 17:21:31 +00:00
{
2021-05-01 15:41:40 +00:00
qDebug()<<QString::fromStdString(mTcp->readAll().toStdString());
2021-05-02 18:02:25 +00:00
emit(on_data_recv());
2021-04-24 17:21:31 +00:00
}
2021-04-29 14:26:45 +00:00
void NetworkController::on_disconect()
2021-04-24 17:21:31 +00:00
{
2021-05-01 15:41:40 +00:00
qDebug()<<"close";
2021-05-02 18:02:25 +00:00
if(nullptr != mCnn){
emit(this->on_conection_close());
mCnn->close();
}
2021-04-24 17:21:31 +00:00
}
2021-05-02 18:02:25 +00:00
void NetworkController::on_server_accept()
{
if(mType == TYPE_TCP_SERVER){
mTcpServer->pauseAccepting();
QTcpSocket* pClientConnection = mTcpServer->nextPendingConnection();
if(nullptr != pClientConnection){
QObject::connect(pClientConnection, SIGNAL(readyRead()), this, SLOT(on_ready_read()));
QObject::connect(pClientConnection, SIGNAL(disconnected()), this, SLOT(on_disconect()));
}
mTcp = pClientConnection;
}
}
NetworkController::NetWorkType NetworkController::_checkType(NetWorkType type){
if(type < TYPE_UNKOWN){
return type;
}else{
return TYPE_UNKOWN;
}
}