Qt默认的QTcpServer有新的连接时会触发newConnection信号,在其对应的槽函数中new QTcpSocket,
通过new的QTcpSocket对象接受发送数据,当有多客户端连接时,Server端接受的数据将不容易分辨是哪个客户端的socket发送的数据,解决这个问题的办法是重写QTcpServer中的incomingConnection(qintptr handle)函数,当有新的连接时,会调用该函数,在该函数中new 一个Socket的,并将函数中的参数handle传递给new的socket作为该socket的ID,这样当有数据发送到server端的时候,就可以知道是哪个客户端的socket。这里需要派生一个QTcpSocketlei用于接收handle作为socket的ID。具体代码实现如下:
派生QTcpSocket:
#ifndef TCPSOCKET_H
#define TCPSOCKET_H
#include <QObject>
#include <QTcpSocket>
class TcpSocket : public QTcpSocket
{
Q_OBJECT
public:
TcpSocket(const int handle);
void slot_readData();
signals:
void sig_disconnect(int);
void sig_readyRead(int, const QByteArray&);
private slots:
void slot_disconnect();
private:
int m_handle;
};
#endif // TCPSOCKET_H
#include "TcpSocket.h"
TcpSocket::TcpSocket(const int handle) : m_handle(handle)
{
this->setSocketDescriptor(m_handle);
connect(this,&TcpSocket::disconnected,this,&TcpSocket::slot_disconnect);
connect(this,&TcpSocket::readyRead,this,&TcpSocket::slot_readData);
}
void TcpSocket::slot_disconnect()
{
emit sig_disconnect(m_handle);
}
void TcpSocket::slot_readData()
{
QByteArray data = readAll();
emit sig_readyRead(m_handle, data);
}
派生QTcpServer,重写incomingConnection(qintptr handle)函数
#ifndef TCPSERVER_H
#define TCPSERVER_H
#