这是作者第一次接触HTML、JavaScript及WebSocket编程,目的是尽快做到简单的应用,程序若有任何理解不对、编程错误或优化方法欢迎指正。
//在pro文件中添加websocket类声明
QT += websockets
//在头文件中添加相关声明及定义
/*添加WebSocket相关头文件*/
#include
#include
/**********************/
/*添加相关槽函数*/
void onNewConnection(); //server端连接到新socket
void Receive_Client_Message(const QString &message); //server端接收到client端消息
void Receive_Server_Message(const QString &message); //client端接收到server端消息
/*************/
/*添加相关定义*/
QWebSocket *client;
QWebSocketServer *server;
QList<QWebSocket*> clientList;
/***********/
/*
* 创建QT WebSocket Server端
* Server侦听ui界面指定的HostAddress及Port
* 将QT WebSocketServer newConnection信号与 ui界面onNewConnection槽函数绑定
*/
void MainWindow::on_Open_Socket_Server_clicked()
{
server = new QWebSocketServer("Server", QWebSocketServer::NonSecureMode, this);
if(!ui->line_HostAddress->text().isEmpty() && !ui->Line_Port->text().isEmpty())
{
if(server->listen(QHostAddress(ui->line_HostAddress->text()), ui->Line_Port->text().toUInt()))
{
qDebug() << "server listen to " << QHostAddress(ui->line_HostAddress->text()).toString() << "port:" << ui->Line_Port->text().toUInt();
connect(server, &QWebSocketServer::newConnection, this, &MainWindow::onNewConnection);
}
}
}
/*
* 创建QT WebSocket Client端
* Client 连接到ui界面指定的URL
* 将QT WebSocket textMessageReceived信号与 ui界面Receive_Server_Message槽函数绑定
*/
void MainWindow::on_Open_Socket_Client_clicked()
{
client = new QWebSocket;
if(!ui->Line_URL->text().isEmpty())
{
client->open(QUrl(ui->Line_URL->text()));
if(!client->requestUrl().isEmpty())
qDebug() << "client connect to" << QString(client->requestUrl().toString());
connect(client, &QWebSocket::textMessageReceived, this, &MainWindow::Receive_Server_Message);
}
}
/*
* 获取server下 第一个socket
* qt的websocket server本身只有listen功能 发送和接收消息需要依靠server建立一个属于自己的websocket来接收和发送来自client的消息
*/
void MainWindow::on_Server_send_clicked()
{
QWebSocket *server_send_socket = clientList[0];
server_send_socket->sendTextMessage(ui->Server_message->text());
}
/*
* client发送消息
*/
void MainWindow::on_Client_send_clicked()
{
client->sendTextMessage(ui->Client_message->text());
}
/*
* server检测到了新连接
* server建立自己的websocket用于接收来自新连接的消息
* 属于server的websocket将其 textMessageReceived信号与ui界面 Receive_Client_Message槽函数绑定
*/
void MainWindow::onNewConnection()
{
qDebug() << "new connection build";
QWebSocket *server_socket = server->nextPendingConnection();
if(!server_socket)
return;
clientList.push_back(server_socket);
connect(server_socket, &QWebSocket::textMessageReceived, this, &MainWindow::Receive_Client_Message);
}
/*
* 打印来自client端消息 以实时时间为标识
*/
void MainWindow::Receive_Client_Message(const QString &message)
{
QTime current_time = QTime::currentTime();
ui->text_Server->append(QString(current_time.toString()) + " " + QString(message));
}
/*
* 打印来自server端消息 以实时时间为标识
*/
void MainWindow::Receive_Server_Message(const QString &message)
{
QTime current_time = QTime::currentTime();
ui->text_Client->append(QString(current_time.toString()) + " " +QString(message));
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Websocket Clienttitle>
head>
<body>
<script src="WebClient.js">script>
body>
html>
var WebClient_websocket = null; //定义网页websocket
//网页初始化加载时触发onload函数
//通过js写入控件
window.onload = function(){
var div = document.createElement("div");
var label_url = document.createElement("p"); //URL标签
var url_address = document.createElement("input"); //URL地址输入框
var confirm = document.createElement("input"); //websocket创建 确认按钮
var receive_message = document.createElement("input"); //websocket接收消息 显示
var send_message = document.createElement("input"); //输入websocket要发送的消息
var send = document.createElement("input"); //websocket发送 确认按钮
//设置URL标签属性及显示值
label_url.type = "text";
label_url.innerText = "Client WebSocket URL: ";
label_url.style.cssText = "text-aligh:center; margin:0 10px; display:inline";
//URL地址输入框属性设置
url_address.value = "ws://192.168.1.40:26";
url_address.id = "ws_address_input";
//websocket创建 确认按钮属性设置
confirm.type = "submit";
confirm.value = "Open";
confirm.style.cssText = "text-aligh:center; margin:0 10px";
//websocket接收消息 显示框属性设置
receive_message.type = "text";
receive_message.id = "message frame";
receive_message.placeholder = "Message from Qt Server";
receive_message.style.cssText = "position: absolute; left:10px; top:35px; width:425px";
//websocket发送消息框属性设置
send_message.type = "text";
send_message.id = "message to send";
send_message.placeholder = "Message to Qt Server";
send_message.style.cssText = "position: absolute; left:10px; top:60px; width:375px";
//websocket发送 确认按钮属性设置
send.type = "submit";
send.value = "Send";
send.style.cssText = "text-aligh:center; position:absolute; left:395px; top:60px";
div.style.setProperty("z-index", 1000);
div.style.setProperty("text-aligh", "center");
div.appendChild(label_url);
div.appendChild(url_address);
div.appendChild(confirm);
div.appendChild(receive_message);
div.appendChild(send_message);
div.appendChild(send);
document.body.appendChild(div);
//websocket创建 确认按钮的点击事件触发websocket初始化
confirm.onclick = function(){
initWebSocket();
}
//websocket发送 确认按钮的点击事件触发WebClient websocket消息发送
send.onclick = function(){
var data = document.getElementById("message to send").value;
WebClient_websocket.send(data);
}
}
//WebSocket 开启函数 将会在控制台打印开启信息及向QT server端发送开启消息
function webSocketOnOpen(){
console.log("open websocket");
WebClient_websocket.send("web open websocket");
}
//WebSocket 接收消息处理函数
function webSocketOnReceiveMessage(msgEvent){
console.log("receive message from Qt server");
var msg = msgEvent.data;
var display = document.getElementById("message frame");
display.value = msg;
}
//WebSocket 错误处理函数
function webSocketOnError(){
console.log("websocket occur error");
}
//WebSocket 关闭函数
function webSocketOnClose(){
console.log("close websocket");
WebClient_websocket = null;
}
//初始化Web端 WebSocket函数
function initWebSocket(){
if(WebClient_websocket == null){
console.log("building websocket");
var url = document.location.host;
var ws_addr = document.getElementById("ws_address_input").value;
WebClient_websocket = new WebSocket(ws_addr);
WebClient_websocket.onopen = webSocketOnOpen;
WebClient_websocket.onmessage = webSocketOnReceiveMessage;
WebClient_websocket.onerror = webSocketOnError;
WebClient_websocket.onclose = webSocketOnClose;
}
}
以上通过简单的QT后端程序和Web前端实现了前后端的WebSocket通讯
WebSocket前后端简单测试工程 提取码:ki9n