QTcpServer多个TcpSocket连接

这篇博客探讨了在QTcpServer中处理多个TCP连接的问题。由于QObject及其派生类不支持复制,因此使用指针来保存connections以避免编译错误。内容提到了将代码片段从完整程序中剥离,可能需要根据实际需求进行调整。
摘要由CSDN通过智能技术生成
//connection类
#ifndef CONNECTION_H
#define CONNECTION_H
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QList>
#include <QMutex>

class Connection:public QObject
{
	Q_OBJECT
public:
	int m_nSocketID;//-1 indicate the socket is invalid; else is the global id of the connection
	int m_nMsgReceived;
	int m_nMsgSent;
	QTcpSocket* m_pTcpSocket;
public:
	Connection(){m_nSocketID = -1;}
	~Connection()
	{
		if (m_pTcpSocket!=NULL)
		{
			delete m_pTcpSocket;
		}
	}
public:
	void InitializeConnection(QTcpSocket* socket, int id)
	{
		m_pTcpSocket = socket;
		m_pTcpSocket->setParent(this);
		m_nMsgReceived = 0;
		m_nMsgSent = 0;
		m_nSocketID = id;
	}
	void DeleteConnection()
	{
		m_nSocketID = -1;
		m_pTcpSocket->disconnect();
	//	delete m_pTcpSocket; 若delete会报错, ?
		m_pTcpSocket = NULL;
	}
};

#endif
//server.h
#ifndef SERVER_H
#define SERVER_H

#include <QtGui/QMainWindow>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QList>
#include <QMutex>
#include "ui_base.h"
#include "qtheader.h"
#include "Connection.h"

class Server : public QMainWindow
{
	Q_OBJECT
public:
	Server(QWidget *parent = 0, Qt::WFlags flags = 0);
	~Server();
	private:
	Ui::BaseClass ui;
public://public variables
	QTcpServer* m_pTcpServer;
	Connection* m_pConnection;	
	QMutex m_mutexConnection;//mutex to protect the array
	int m_nConnected;
	int m_nID;
public:
	bool InitializeServers();
	void ShowStatusMessage(con
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值