来一段自封装,在用的QTcpserver,不用去找boost,或是poco,libevent……,也不用去从底层winsocket封装开始,真不用去那么折腾,放着QT自带的不用,那不仅是可惜,是辜负了QT团队的一片苦心……
#pragma once
#include <atomic>
#include <QTcpServer>
#include <QTcpSocket>
#include <QList>
#include <QTimer>
#include <QTcpServer>
#include <mutex>
#include <QObject>
class LQTcpServer :public QObject
{
Q_OBJECT
public:
LQTcpServer();
explicit LQTcpServer(const int svPort);
~LQTcpServer();
QString getSockID(QTcpSocket * mclient) const;
void setServerPort(const int svPort);
public:
bool isServerRun() { return isServerRunning; }
bool sendMSG(std::string strData);
bool sendData(char* data, const int slen);
bool sendData(QByteArray data);
void releaseServer();
/*
res:0 已经运行了
1:运行成功,-1:启动tcpserver失败
*/
int startServer();
bool pause();
bool resume();
signals:
void onClientConnected(QTcpSocket* sender, QString senderInfo);
void onClientDisconnected(QString senderInfo);
void onServerRead(QTcpSocket* sender,const QByteArray mRevData,QString senderInfo);
protected:
QList<QTcpSocket *> clients;
QTcpServer* mGServer;
//QTcpSocket* connectClient;
protected slots:
void new_client();
void distconnect_client();
void read_data();
private:
int mServerPort;
std::atomic_bool isServerRunning;
};