qt 使用tcp 发送文件,100个套接字100个线程,怎么调用其中某个套接字发送?
时间: 2023-11-22 09:56:24 浏览: 37
在使用Qt的TCP套接字发送文件时,可以考虑使用QThread来实现多线程发送。可以将每个套接字与一个线程绑定,这样就可以在不阻塞主线程的情况下同时发送多个文件。以下是一个简单的示例代码:
```cpp
class TcpThread : public QThread
{
Q_OBJECT
public:
TcpThread(QObject *parent = nullptr) : QThread(parent), m_socket(nullptr)
{
connect(this, SIGNAL(finished()), this, SLOT(deleteLater()));
}
~TcpThread()
{
if (m_socket != nullptr)
{
m_socket->disconnectFromHost();
delete m_socket;
}
}
void setSocket(QTcpSocket *socket)
{
m_socket = socket;
}
void setFilePath(const QString &filePath)
{
m_filePath = filePath;
}
signals:
void error(QTcpSocket::SocketError socketError);
protected:
void run() override
{
QFile file(m_filePath);
if (!file.open(QIODevice::ReadOnly))
{
qDebug() << "File open error!";
return;
}
while (!file.atEnd())
{
QByteArray data = file.read(1024);
if (m_socket->write(data) == -1)
{
emit error(m_socket->error());
return;
}
}
file.close();
m_socket->disconnectFromHost();
}
private:
QTcpSocket *m_socket;
QString m_filePath;
};
```
使用示例:
```cpp
void sendFile(QString filePath, QTcpSocket *socket)
{
TcpThread *thread = new TcpThread();
thread->setSocket(socket);
thread->setFilePath(filePath);
thread->start();
}
```
在使用时,只需要创建一个QTcpSocket对象并连接到服务器,然后调用sendFile函数即可开启一个新的线程发送文件。如果需要停止某个套接字的发送,则可以通过TcpThread类中的m_socket成员变量获取到对应的QTcpSocket对象,并调用disconnectFromHost()函数断开连接。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)