Qt webserver

pro:

QT += core websockets

server:

#include "echoserver.h"
#include "QtWebSockets/qwebsocketserver.h"
#include "QtWebSockets/qwebsocket.h"
#include 
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(sender());
    //if (m_debug)
        qDebug() << "Message received:" << message;
    if (pClient) {
        pClient->sendTextMessage(QString("服务器收到了") + message);
    }
}
void EchoServer::processBinaryMessage(QByteArray message)
{
    QWebSocket *pClient = qobject_cast(sender());
    //if (m_debug)
        qDebug() << "Binary Message received:" << message;
    if (pClient) {
        pClient->sendBinaryMessage(message);
    }
}
void EchoServer::socketDisconnected()
{
    QWebSocket *pClient = qobject_cast(sender());
    //if (m_debug)
        qDebug() << "socketDisconnected:" << pClient;
    if (pClient) {
        m_clients.removeAll(pClient);
        pClient->deleteLater();
    }
}

client:

#include "echoclient.h"
#include 
#include 
#include 
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 Clienttitle>
    head>
    <body>
        <h1>WebSocket Echo Clienth1>
        <p>
            <button onClick="initWebSocket();">Connectbutton>
            <button onClick="stopWebSocket();">Disconnectbutton>
            <button onClick="checkSocket();">Statebutton>
        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();">Sendbutton>
        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>

效果:
Qt webserver_第1张图片
代码链接:https://github.com/yangyang0312/cpp/tree/master/Qt/webserver

你可能感兴趣的:(QT,qt,web,server)