//网络发送日志数据类标签:QT,listenPort,self,SendLog,网络,server,NULL,socket From: https://blog.51cto.com/u_15515702/5789379
QScopedPointer<SendLog> SendLog::self;
SendLog *SendLog::Instance()
{
if (self.isNull()) {
static QMutex mutex;
QMutexLocker locker(&mutex);
if (self.isNull()) {
self.reset(new SendLog);
}
}
return self.data();
}
SendLog::SendLog(QObject *parent) : QObject(parent)
{
listenPort = 6000;
socket = NULL;
//实例化网络通信服务器对象
server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
}
SendLog::~SendLog()
{
if (socket != NULL) {
socket->disconnectFromHost();
}
server->close();
}
void SendLog::newConnection()
{
//限定就一个连接
while (server->hasPendingConnections()) {
socket = server->nextPendingConnection();
}
}
void SendLog::setListenPort(int listenPort)
{
this->listenPort = listenPort;
}
void SendLog::start()
{
//启动端口监听
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
server->listen(QHostAddress::AnyIPv4, listenPort);
#else
server->listen(QHostAddress::Any, listenPort);
#endif
}
void SendLog::stop()
{
if (socket != NULL) {
socket->disconnectFromHost();
socket = NULL;
}
server->close();
}
void SendLog::send(const QString &content)
{
if (socket != NULL && socket->isOpen()) {
socket->write(content.toUtf8());
//socket->flush();
}