直接给出QServer的测试代码
在pro文件中添加network不然会报错找不到文件
mysocket.h如下:
#ifndef MYSOCKET_H
#define MYSOCKET_H
#include <QTcpServer>
#include <QTcpSocket>
#include <QObject>
class MySocket: public QObject
{
Q_OBJECT
public:
MySocket();
void sendData(QString msg);
void startRunSocket(QString ip, int port);
void closeSocket();
signals:
void clientData(QString msg);
private slots:
void connectServer();
void disconnectServer();
void readClient();
private:
QTcpServer* m_pTcpServer;
QTcpSocket* m_client;
};
#endif // MYSOCKET_H
mysocket.cpp如下:
#include "mysocket.h"
#include <QDebug>
MySocket::MySocket()
{
this->m_pTcpServer = new QTcpServer();
connect(m_pTcpServer, &QTcpServer::newConnection, this, &MySocket::connectServer);
this->m_client = nullptr;
}
void MySocket::sendData(QString msg)
{
if(this->m_client == nullptr)
{
return;
}
this->m_client->write(msg.toUtf8());
}
void MySocket::startRunSocket(QString ip, int port)
{
if(this->m_pTcpServer == nullptr)
{
this->m_pTcpServer = new QTcpServer();
connect(m_pTcpServer, &QTcpServer::newConnection, this, &MySocket::connectServer);
this->m_client = nullptr;
}
bool ret = this->m_pTcpServer->listen(QHostAddress(ip), port);
if(!ret)
{
qDebug() << "TCP Server Listen Error!";
}
}
void MySocket::closeSocket()
{
if(this->m_client)
{
this->m_client->close();
this->m_client->deleteLater();
this->m_client = nullptr;
}
this->m_pTcpServer->close();
this->m_pTcpServer = nullptr;
}
void MySocket::connectServer()
{
this->m_client = this->m_pTcpServer->nextPendingConnection();
//建立链接函数
connect(m_client, &QTcpSocket::readyRead, this, &MySocket::readClient);
connect(m_client, &QTcpSocket::disconnected, this, &MySocket::disconnectServer);
this->sendData("hello client!");
}
void MySocket::disconnectServer()
{
this->m_client->close();
this->m_client->deleteLater();
this->m_client = nullptr;
}
void MySocket::readClient()
{
QByteArray data = this->m_client->readAll();
qDebug() << "get data :" << data;
emit clientData(data);
}