下面是一个示例代码,展示如何使用Qt编写一个服务端接收和客户端交互的接口。
服务端代码:
#include <QtCore/QCoreApplication>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
class Server : public QObject
{
Q_OBJECT
public:
explicit Server(QObject *parent = nullptr)
: QObject(parent), m_server(nullptr)
{
m_server = new QTcpServer(this);
connect(m_server, &QTcpServer::newConnection, this, &Server::onNewConnection);
if (m_server->listen(QHostAddress::Any, 1234))
qInfo() << "Server started on port" << m_server->serverPort();
else
qWarning() << "Failed to start server!";
}
signals:
void messageReceived(const QString &message);
private slots:
void onNewConnection()
{
QTcpSocket *socket = m_server->nextPendingConnection();
connect(socket, &QTcpSocket::readyRead, this, [this, socket]() {
QByteArray data = socket->readAll();
QString message(data);
emit messageReceived(message); // Forward the received message to the main thread for handling
// Example: Echo back the received message to the client
socket->write(data);
});
connect(socket, &QTcpSocket::disconnected, this, [this]() {
QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
if (socket) {
socket->deleteLater();
qInfo() << "Client disconnected";
}
});
qInfo() << "New client connected:" << socket->peerAddress().toString() << ":" << socket->peerPort();
}
private:
QTcpServer *m_server;
};
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
Server server;
QObject::connect(&server, &Server::messageReceived, [](const QString &message) {
qInfo() << "Received message:" << message;
});
return app.exec();
}
#include "main.moc"
客户端代码:
#include <QtCore/QCoreApplication>
#include <QtNetwork/QTcpSocket>
class Client : public QObject
{
Q_OBJECT
public:
explicit Client(QObject *parent = nullptr)
: QObject(parent), m_socket(nullptr)
{
m_socket = new QTcpSocket(this);
connect(m_socket, &QTcpSocket::connected, this, [this]() {
qInfo() << "Connected to server";
// Example: Send a message to the server
m_socket->write("Hello from client");
});
connect(m_socket, &QTcpSocket::readyRead, this, [this]() {
QByteArray data = m_socket->readAll();
QString message(data);
emit messageReceived(message); // Forward the received message to the main thread for handling
qInfo() << "Received response:" << data;
m_socket->close(); // Close the connection after receiving the response
});
connect(m_socket, static_cast<void(QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::errorOccurred), this,
[this](QAbstractSocket::SocketError socketError){
qWarning() << "Connection error:" << socketError;
if (m_socket->state() == QAbstractSocket::UnconnectedState)
m_socket->deleteLater();
});
m_socket->connectToHost("localhost", 1234); // Connect to the server
}
signals:
void messageReceived(const QString &message);
private:
QTcpSocket *m_socket;
};
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
Client client;
QObject::connect(&client, &Client::messageReceived, [](const QString &message) {
qInfo() << "Received message:" << message;
});
return app.exec();
}
#include "main.moc"
上述代码演示了一个简单的TCP服务端和客户端通信。服务端接收来自客户端的消息,并将其原样返回给客户端。你可以根据需求在服务端和客户端中实现更复杂的交互逻辑。
请注意,这是一个基本示例,并没有处理异常情况或错误处理。在实际应用中,请根据需要进行适当的错误处理和容错机制。
确保正确安装并链接QtNetwork模块。
内容由零声教学AI助手提供,问题来源于学员提问