QTcpServer收发消息
时间: 2024-10-19 22:06:12 浏览: 13
QTcpserver 服务器
3星 · 编辑精心推荐
在Qt中,一旦`QTcpServer`接收到新的连接,你可以通过创建一个`QTcpSocket`对象来与每个客户端通信。以下是一个基本的收发消息的例子:
```cpp
class MyClientHandler : public QObject
{
Q_OBJECT
QTcpSocket *m_clientSocket;
public:
explicit MyClientHandler(QTcpSocket *client, QObject *parent = nullptr)
: QObject(parent), m_clientSocket(client)
{
connect(m_clientSocket, &QTcpSocket::readyRead, this, &MyClientHandler::readDataFromClient);
connect(m_clientSocket, &QTcpSocket::disconnected, this, &MyClientHandler::handleDisconnection);
}
private slots:
void readDataFromClient()
{
QByteArray data = m_clientSocket->readAll(); // 读取客户端发送的数据
QString message = QString::fromUtf8(data.data());
// 处理接收到的消息,例如打印或转发给其他服务
qDebug() << "Received from client: " << message;
}
void handleDisconnection()
{
qDebug() << "Client disconnected";
deleteLater(); // 清理资源
}
public slots:
void sendDataToClient(const QString &message)
{
QByteArray encodedMessage = message.toUtf8();
m_clientSocket->write(encodedMessage); // 发送数据到客户端
}
};
```
当你在`QTcpServer`的`newConnection`信号处理器中创建并传递`MyClientHandler`实例给每个新连接的客户端时,就可以通过`sendDataToClient`方法向他们发送数据,而`readDataFromClient`则会读取并处理来自客户端的消息。
阅读全文