smart-greenhouse/cnetworkutil.cpp
2022-01-20 17:29:47 +08:00

90 lines
1.6 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "cnetworkutil.h"
/*
* TODO:
* 1、receive buffer
* 2、receive callback(connect signal & slot)
* 3、buffer reader
*/
//这是一个全局变量
CNetWorkUtil *networkUtil = new CNetWorkUtil;
//构造函数是空的
CNetWorkUtil::CNetWorkUtil()
{
}
//以默认参数连接 ip 127.0.0.1 port 8080
void CNetWorkUtil::connect()
{
//qDebug(this->m_ip.toUtf8());
this->m_tcpSocket.connectToHost(this->m_ip,this->m_port);
}
//连接指定参数网址
void CNetWorkUtil::connect(QString ip, int port)
{
this->setIp(ip);
this->setPort(port);
this->connect();
}
//设置连接的ip
void CNetWorkUtil::setIp(QString ip)
{
this->m_ip = ip;
}
//获取当前连接的ip
QString CNetWorkUtil::getIp()
{
return this->m_ip;
}
//设置端口号
void CNetWorkUtil::setPort(int port)
{
this->m_port = port;
}
//获取当前连接的端口号
int CNetWorkUtil::getPort()
{
return this->m_port;
}
//判断当前是否连接
bool CNetWorkUtil::isConnected()
{
return this->m_tcpSocket.state() == QAbstractSocket::ConnectingState;
}
//断开网络
void CNetWorkUtil::disconnect()
{
//断开连接断开关联
this->m_tcpSocket.disconnect(&this->m_tcpSocket, SIGNAL(connected()), nullptr, nullptr);
this->m_tcpSocket.disconnect(&this->m_tcpSocket, SIGNAL(disconnected()), nullptr, nullptr);
this->m_tcpSocket.disconnectFromHost();
this->m_tcpSocket.close();
}
//获取tcpSocket对象
QTcpSocket &CNetWorkUtil::getTcpSocket()
{
return this->m_tcpSocket;
}
//发送消息
void CNetWorkUtil::sendMsg(QString msg)
{
this->m_tcpSocket.write(msg.toUtf8(),strlen(msg.toUtf8()));
}