当前位置:   article > 正文

Qt下实现线程中的TCP服务器_qtcpserver放入线程

qtcpserver放入线程

简述

TCP服务器的代码实现比UDP略为复杂一点,因为TCP的服务端需要生成与管理一个额外的QTcpServer对象。为了支持多线程,用moveToThread方法把服务器放在一个单独的线程中。

代码之路

用MyTcpServer类实现TCPserver,供主程序调用方法。
MyTcpServer类头文件内容如下:

//MyTcpServer.h
# include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QThread>
#include <QDebug>

class MyTcpServer : public QObject
{
	Q_OBJECT
public:
	explicit MyTcpServer(QObject *parent = 0);
	~MyTcpServer();
signals:
	void dataArrive(QByteArray ba); //send data to deal
public slots:
	void onNewConnection(); //new connection come
	void socketReaddata();    //read socket data
private:
	QTcpServer *m_tcpserver;
	QTcpSocket *m_socket;
	QByteArray tmpdata;
	QThread *m_thread;
	int tcpPort = 6000;
	QByteArray m_buffer;	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

MyTcpServer类的源文件如下:

//MyTcpServer.cpp
MyTcpServer::MyTcpServer(QObject *parent) : QObject(parent)
{
	m_thread = new QThread();
	m_tcpserver = new QTcpServer();
	connect(m_tcpserver, &QTcpServer::newConnection, this, &MyTcpServer::onNewConnection, Qt::DirectConnection);
	if (!m_tcpserver->listen(QHostAddress::AnyIPv4, 6000)
	{
		m_tcpserver->close();
		qDebug()<< "tcplistenerror:" << m_tcpserver->errorString();
	}
	this->moveToThread(m_thread);
	m_tcpserver->moveToThread(m_thread);
	m_thread->start();
}

MyTcpServer::~MyTcpServer()
{
	m_thread->quit();
	m_thread->wait();
	delete m_thread;
	m_tcpserver->close();
	delete m_tcpserver;
}

void MyTcpServer::onNewConnection()
{
	QTcpSocket *socket_temp = m_tcpserver->nextPendingConnection();
	m_socket = socket_temp;
	qDebug() << "new TCPconnection come.";
	connect(socket_temp, SIGNAL(readyRead()), this, SLOT(socketReaddata()));
	connect(socket_temp, SIGNAL(disconnected()), this, SLOT(socketDisconnect()));
}

//读取info,发送给类外的接收槽处理
void MyTcpServer::socketReaddata()
{
	if (m_socket->bytesAvailable() <= 0
	{
		return;
	}
	m_buffer = m_socket->readAll();
	tmpdata.clear();
	tmpdata = m_buffer.left(20);
	m_buffer.remove(0, 20);
	emit dataArrive(tmpdata);
}

void MyTcpServer::socketDisconnect()
{
	m_socket->deleteLater();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

总结

文中的TCP服务器业务逻辑很简单,监听端口号6000,每收到数据取头20个字节并发送,复杂的逻辑可以改写socketReaddata函数。
在工程的pro文件中不要忘记把network模块加入进来。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/187352
推荐阅读
相关标签
  

闽ICP备14008679号