用qt写出websocket服务端和客户端的代码,需要加上注释
时间: 2023-03-26 12:03:19 浏览: 164
好的,以下是用Qt写出WebSocket服务端和客户端的代码,已经加上注释:
服务端代码:
#include <QtCore/QCoreApplication>
#include <QtWebSockets/QWebSocketServer>
#include <QtWebSockets/QWebSocket>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QWebSocketServer server(QStringLiteral("WebSocket Server"), QWebSocketServer::NonSecureMode);
if (!server.listen(QHostAddress::Any, 1234)) { // 监听所有IP地址,端口号为1234
qFatal("Failed to listen on port 1234.");
return 1;
}
QObject::connect(&server, &QWebSocketServer::newConnection, [&server]() {
QWebSocket *socket = server.nextPendingConnection();
QObject::connect(socket, &QWebSocket::textMessageReceived, [socket](const QString &message) {
qDebug() << "Received message:" << message;
socket->sendTextMessage(QStringLiteral("Echo: %1").arg(message)); // 回复客户端
});
});
qDebug() << "WebSocket server started on port 1234.";
return a.exec();
}
客户端代码:
#include <QtCore/QCoreApplication>
#include <QtWebSockets/QWebSocket>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QWebSocket socket;
QObject::connect(&socket, &QWebSocket::connected, [&socket]() {
qDebug() << "Connected to server.";
socket.sendTextMessage(QStringLiteral("Hello, server!")); // 发送消息给服务端
});
QObject::connect(&socket, &QWebSocket::textMessageReceived, [](const QString &message) {
qDebug() << "Received message:" << message;
});
socket.open(QUrl(QStringLiteral("ws://localhost:1234"))); // 连接到服务端
return a.exec();
}
希望这个代码能够帮到你。
阅读全文