proto-debuger/protoDebuger/network_controller.cpp

134 lines
3.3 KiB
C++

#include "network_controller.h"
NetworkController::NetworkController(NetworkController::NetWorkType type,
QString ip,
uint16_t port):mTcp(nullptr),
mUDP(nullptr),
mTcpServer(nullptr),
mCnn(nullptr)
{
mType = type;
if(_checkType(type) == TYPE_UNKOWN){
}
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);
}
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( on_accept_error(QAbstractSocket::SocketError socketError)));
if (!mTcpServer->listen(QHostAddress::Any, port))
{
qDebug() << "m_pTcpServer->listen() error";
}
}
if((type == NetWorkType::TYPE_UDP_SERVER) || (type == NetWorkType::TYPE_TCP_CLIENT)){
mUDP = new QUdpSocket(this);
mUDP->bind(QHostAddress::LocalHost, port);
mCnn = mUDP;
connect(mUDP, SIGNAL(readyRead()),
this, SLOT(on_ready_read()));
}
}
int NetworkController::SendData(int8_t *data, uint32_t len)
{
if(nullptr == data)
return -1;
return mCnn->write((const char *)data,len);
}
int NetworkController::ReadData(int8_t *data)
{
if(nullptr != data){
return -1;
}
memcpy(data,mCnn->readAll().data(),mCnn->size());
}
int NetworkController::Close()
{
if(mType == TYPE_TCP_SERVER){
mTcpServer->close();
if(nullptr != mCnn)
mCnn->close();
delete mTcpServer;
delete mCnn;
}
if(mType == TYPE_TCP_CLIENT){
mCnn->close();
}
return 0;
}
NetworkController::~NetworkController()
{
delete mTcp;
delete mCnn;
delete mTcpServer;
delete mUDP;
}
void NetworkController::on_ready_read()
{
qDebug()<<QString::fromStdString(mCnn->readAll().toStdString());
emit(on_data_recv());
}
void NetworkController::on_disconect()
{
qDebug()<<"close";
if(nullptr != mCnn){
mCnn->close();
emit(this->on_conection_close());
}
if(mType == TYPE_TCP_SERVER){
mTcpServer->resumeAccepting();
}
}
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;
mCnn = mTcp;
qDebug()<<"on_server_accept";
}
}
void NetworkController::on_accept_error(QAbstractSocket::SocketError socketError)
{
qDebug()<<socketError;
}
NetworkController::NetWorkType NetworkController::_checkType(NetWorkType type){
if(type < TYPE_UNKOWN){
return type;
}else{
return TYPE_UNKOWN;
}
}