代码:
#include "SocketApp.h"
SocketApp::SocketApp(QString strIP,QString strNetModel , int iPort)
:onNum(0),
m_strNetModel(strNetModel),
isCheckServer(true),
isServer(true),
isCheckClient(false)
{
recvSize = 0;
sendSize = 0;
m_TcpSocket = NULL;
m_UdpSocket = NULL;
mServer = NULL;
m_strIP = strIP;
m_iPort = iPort;
StartBtSocket();
}
SocketApp::~SocketApp()
{
}
//与newconnection信号关联
void SocketApp::accept_connect()
{
m_TcpSocket = mServer->nextPendingConnection(); //返回与客户端连接通信的套接字
clients.append(m_TcpSocket);
connect(m_TcpSocket, SIGNAL(readyRead()), this, SLOT(recv_data()));
//关联掉线信号
connect(m_TcpSocket, SIGNAL(disconnected()), this, SLOT(client_disconnect()));
}
//接收数据
void SocketApp::recv_data()
{
QTcpSocket *obj = (QTcpSocket*)sender();
//获取发送数据端的IP
QString ip = obj->peerAddress().toString();
ip.remove("::ffff:");
QString msg = obj->readAll();
recvSize += msg.size();//统计接收到的数据的字节数
newCommandAccept(msg);
}
void SocketApp::client_disconnect()
{
QTcpSocket *obj = (QTcpSocket*)sender();//获取掉线对象
if (isServer)
{
int row = clients.indexOf(obj);//找到掉线对象的内容所在的行
clients.remove(row);//从容器中删除对象
//掉线时删除在线数量
onNum--;
}
else
{
}
}
//客户端连接成功
void SocketApp::connect_suc()
{
}
//发送数据
void SocketApp::sendData()
{
if (m_strNetModel == "TCP")
{
if (m_TcpSocket == NULL)
return;
quint64 len = m_TcpSocket->write(m_strAction.toLocal8Bit());
if (len > 0)
{
sendSize += len;//统计发送的字节数
}
}
else
{
QByteArray msg = QString::fromLocal8Bit("发送指令").toLocal8Bit();
m_UdpSocket->writeDatagram(msg, QHostAddress(m_strIP), m_iPort);
}
}
//启动服务器或者链接服务器
void SocketApp::StartBtSocket()
{
if (isServer) //服务器
{
mServer = new QTcpServer();
bool bRet = mServer->listen(QHostAddress(m_strIP), m_iPort);//启动服务器监听
//关联新客户端链接信号
connect(mServer, SIGNAL(newConnection()), this, SLOT(accept_connect()));
}
if (isServer == false) //客户端
{
m_TcpSocket = new QTcpSocket();
//检测链接成功信号
connect(m_TcpSocket, SIGNAL(connected()), this, SLOT(connect_suc()));
//设置服务器的 ip和端口号
//m_TcpSocket->connectToHost();
//关联接收数据信号
connect(m_TcpSocket, SIGNAL(readyRead()), this, SLOT(recv_data()));
//关联掉线信号
connect(m_TcpSocket, SIGNAL(disconnected()), this, SLOT(client_disconnect()));
}
m_UdpSocket = new QUdpSocket;
bool bRet = m_UdpSocket->bind(QHostAddress(m_strIP), 8000);
connect(m_UdpSocket, SIGNAL(readyRead()), this, SLOT(receive()));
}
void SocketApp::receive()
{
QByteArray ba;
while (m_UdpSocket->hasPendingDatagrams())
{
ba.resize(m_UdpSocket->pendingDatagramSize());
m_UdpSocket->readDatagram(ba.data(), ba.size());
newCommandAccept(QString(ba.data()));
}
}
//关闭服务器或者断开
void SocketApp::on_closeBt_clicked()
{
if (isServer)//服务器
{
//关闭所有服务器之后开始按钮才能启用
mServer->close();
}
else //客户端
{
m_TcpSocket->close();//关闭客户端
}
}
void SocketApp::setCurrentNetModel(QString str)
{
m_strNetModel = str;
}
void SocketApp::setCurrentAction(QString str)
{
m_strAction = str;
}
bool SocketApp::checkCurrentIPAndPort(QString strIP,int iPort)
{
if (m_strIP == strIP && m_iPort == iPort)
{
return true;
}
else
{
return false;
}
}