QT开发中文网

qt写一个服务端接收和客户端交互接口

下面是一个示例代码,展示如何使用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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=9880

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?