一.前言
楼主在最近的工作中接触到socket方面的知识,而又是接触Qt的多,于是就找了下Qt这方面封装的类,以此来练手熟悉一下
二.关于QwbSocket
Implements a TCP socket that talks the WebSocket protocol. 实现一个与WebSocket协议对话的TCP套接字
WebSockets is a web technology providing full-duplex communications channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011. QWebSocket can both be used in a client application and server application. WebSockets是一种通过单个TCP连接提供全双工通信通道的Web技术。WebSocket协议在2011年被IETF标准化为RFC 6455。QWebSocket既可用于客户端应用程序,也可用于服务器应用程序。
This class was modeled after QAbstractSocket. 这个类是继承了QAbstractSocket
QWebSocket currently does not support WebSocket Extensions and WebSocket Subprotocols. QWebSocket当前不支持WebSocket扩展和WebSocket子工具。
QWebSocket only supports version 13 of the WebSocket protocol, as outlined in RFC 6455. QWebSocket仅支持WebSocket协议的版本13,如RFC6455所述。 三.客户端的实现举例 1.pro文件添加websockets
QT += core gui websockets
2.简单的布局界面 3.核心代码
#include "ClientWidget.h"
#include "ui_ClientWidget.h"
ClientWidget::ClientWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::ClientWidget)
{
ui->setupUi(this);
setWindowTitle("客户端");
connect(&webSocket, SIGNAL(connected()), this, SLOT(onConnected()));
connect(&webSocket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
connect(&webSocket, SIGNAL(textMessageReceived(QString)), this, SLOT(onTextMessageReceived(QString)));
}
ClientWidget::~ClientWidget()
{
delete ui;
}
void ClientWidget::on_pushButton_1_clicked()
{
qDebug()<<"开始新连接";
ui->textEdit_2->append(QDateTime::currentDateTime().toString()+":开始连接");
QString urlStr = QString("ws://%1").arg(ui->lineEdit->text());
webSocket.open(QUrl(urlStr));
}
void ClientWidget::on_pushButton_2_clicked()
{
webSocket.close();
}
void ClientWidget::on_pushButton_3_clicked()
{
ui->textEdit_2->append(QDateTime::currentDateTime().toString()+":给服务端发消息:"+ui->textEdit_1->toPlainText());
webSocket.sendTextMessage(ui->textEdit_1->toPlainText().toLocal8Bit());
}
void ClientWidget::onConnected()
{
ui->textEdit_2->append(QDateTime::currentDateTime().toString()+":正确连接上了服务端");
}
void ClientWidget::onDisconnected()
{
ui->textEdit_2->append(QDateTime::currentDateTime().toString()+":断开连接");
}
void ClientWidget::onTextMessageReceived(QString msg)
{
qDebug()<<msg;
ui->textEdit_2->append(QDateTime::currentDateTime().toString()+":服务端发来消息:"+msg);
}
四.联合服务端效果展示
|