概述
pro:
QT += core websockets
server:
#include "echoserver.h"
#include "QtWebSockets/qwebsocketserver.h"
#include "QtWebSockets/qwebsocket.h"
#include <QtCore/QDebug>
QT_USE_NAMESPACE
EchoServer::EchoServer(quint16 port, bool debug, QObject *parent) :
QObject(parent),
m_pWebSocketServer(new QWebSocketServer(QStringLiteral("Echo Server"),
QWebSocketServer::NonSecureMode, this)),
m_debug(debug)
{
if (m_pWebSocketServer->listen(QHostAddress::Any, port)) {
//if (m_debug)
qDebug() << "Echoserver listening on port" << port;
connect(m_pWebSocketServer, &QWebSocketServer::newConnection,
this, &EchoServer::onNewConnection);
connect(m_pWebSocketServer, &QWebSocketServer::closed, this, &EchoServer::closed);
}
}
EchoServer::~EchoServer()
{
m_pWebSocketServer->close();
qDeleteAll(m_clients.begin(), m_clients.end());
}
void EchoServer::onNewConnection()
{
QWebSocket *pSocket = m_pWebSocketServer->nextPendingConnection();
connect(pSocket, &QWebSocket::textMessageReceived, this, &EchoServer::processTextMessage);
connect(pSocket, &QWebSocket::binaryMessageReceived, this, &EchoServer::processBinaryMessage);
connect(pSocket, &QWebSocket::disconnected, this, &EchoServer::socketDisconnected);
m_clients << pSocket;
}
void EchoServer::processTextMessage(QString message)
{
QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
//if (m_debug)
qDebug() << "Message received:" << message;
if (pClient) {
pClient->sendTextMessage(QString("服务器收到了") + message);
}
}
void EchoServer::processBinaryMessage(QByteArray message)
{
QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
//if (m_debug)
qDebug() << "Binary Message received:" << message;
if (pClient) {
pClient->sendBinaryMessage(message);
}
}
void EchoServer::socketDisconnected()
{
QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
//if (m_debug)
qDebug() << "socketDisconnected:" << pClient;
if (pClient) {
m_clients.removeAll(pClient);
pClient->deleteLater();
}
}
client:
#include "echoclient.h"
#include <QtCore/QDebug>
#include <string>
#include <iostream>
QT_USE_NAMESPACE
EchoClient::EchoClient(const QUrl &url, bool debug, QObject *parent) :
QObject(parent),
m_url(url),
m_debug(debug)
{
// if (m_debug)
qDebug() << "WebSocket server:" << url;
connect(&m_webSocket, &QWebSocket::connected, this, &EchoClient::onConnected);
connect(&m_webSocket, &QWebSocket::disconnected, this, &EchoClient::closed);
m_webSocket.open(QUrl(url));
}
void EchoClient::onConnected()
{
//if (m_debug)
qDebug() << "WebSocket connected";
connect(&m_webSocket, &QWebSocket::textMessageReceived,
this, &EchoClient::onTextMessageReceived);
m_webSocket.sendTextMessage(QStringLiteral("Hello, world!"));
}
void EchoClient::onTextMessageReceived(QString message)
{
//if (m_debug)
qDebug() << "Message received:" << message;
std::string s;
std::cin>>s;
m_webSocket.sendTextMessage(QString::fromStdString(s));
//m_webSocket.close();
}
也可以用js websocket链接:
<html>
<head>
<title>WebSocket Echo Client</title>
</head>
<body>
<h1>WebSocket Echo Client</h1>
<p>
<button onClick="initWebSocket();">Connect</button>
<button onClick="stopWebSocket();">Disconnect</button>
<button onClick="checkSocket();">State</button>
</p>
<p>
<textarea id="debugTextArea" style="width:400px;height:200px;"></textarea>
</p>
<p>
<input type="text" id="inputText" onkeydown="if(event.keyCode==13)sendMessage();"/>
<button onClick="sendMessage();">Send</button>
</p>
<script type="text/javascript">
var debugTextArea = document.getElementById("debugTextArea");
function debug(message) {
debugTextArea.value += message + "n";
debugTextArea.scrollTop = debugTextArea.scrollHeight;
}
function sendMessage() {
var msg = document.getElementById("inputText").value;
if ( websocket != null )
{
document.getElementById("inputText").value = "";
websocket.send( msg );
console.log( "string sent :", '"'+msg+'"' );
}
}
var wsUri = "ws://192.30.1.163:1234";
var websocket = null;
function initWebSocket() {
try {
if (typeof MozWebSocket == 'function')
WebSocket = MozWebSocket;
if ( websocket && websocket.readyState == 1 )
websocket.close();
websocket = new WebSocket( wsUri );
websocket.onopen = function (evt) {
debug("CONNECTED");
};
websocket.onclose = function (evt) {
debug("DISCONNECTED");
};
websocket.onmessage = function (evt) {
console.log( "Message received :", evt.data );
debug( evt.data );
};
websocket.onerror = function (evt) {
debug('ERROR: ' + evt.data);
};
} catch (exception) {
debug('ERROR: ' + exception);
}
}
function stopWebSocket() {
if (websocket)
websocket.close();
}
function checkSocket() {
if (websocket != null) {
var stateStr;
switch (websocket.readyState) {
case 0: {
stateStr = "CONNECTING";
break;
}
case 1: {
stateStr = "OPEN";
break;
}
case 2: {
stateStr = "CLOSING";
break;
}
case 3: {
stateStr = "CLOSED";
break;
}
default: {
stateStr = "UNKNOW";
break;
}
}
debug("WebSocket state = " + websocket.readyState + " ( " + stateStr + " )");
} else {
debug("WebSocket is null");
}
}
</script>
</body>
</html>
效果:
代码链接:https://github.com/yangyang0312/cpp/tree/master/Qt/webserver
最后
以上就是孤独绿茶为你收集整理的Qt webserver的全部内容,希望文章能够帮你解决Qt webserver所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复