基於Qt-socketio客戶端與Nodejs服務器通訊

       Node.Js現在很火?是的,它現在屬於後臺服務器比較火的方案之一,廢話不多說,想了解nodejs自己google去查查,基於javascript的後臺服務器框架
       最近要做PC客戶端的IM工作,而恰好後端使用的nodejs的,做即時通訊等功能,對於nodejs來說應該是綽綽有餘,單線程下的高併發,適合創業公司學習。
       今天上午本來打算使用Qt下面的QTcpSocket來與後端socket.io建立鏈接,不曾想,簡單的socket鏈接 是無法滿足於現狀,於是乎,網上找,羣內問,終於找到了基於Qt下面的websocket的例子,可惜我現在Qt版本是5.2.1,但是Qt5.3已經將websocket模塊集成到啦Qt框架裏面啦,真是蛋疼的不得不用最新的,本來想使用QWebsocket源碼進行編譯,然後與QSocketIO源碼進行編譯成可用的動態庫,但是不曾想,裏面的坑太多,只得安裝新的Qt5.3Beta包,才得以用之。
       現在主要說下QSocketIO的開源代碼,代碼地址:QSocketIO,老外寫的開源的東東,分享精神不錯,還是有QWebsocket這個本來是他開源的,後來直接被Qt收錄囊中,直接集成到模塊,Qt真是個大雜燴,集開源代碼於一身。
       要使用socket.io QSocketIO已經有例子告訴你如何寫。
       簡單說下Qt部分

#include "echoclient.h"
#include <QtSocketIo/QSocketIOClient>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonArray>
#include <QtCore/QDebug>

#define function(args...) [=](args)

EchoClient::EchoClient(QObject *parent) :
    QObject(parent),
    m_client()
{
    QObject::connect(&m_client, SIGNAL(connected(QString)), this, SLOT(connected(QString)));
    QObject::connect(&m_client, SIGNAL(disconnected(QString)), this, SLOT(disconnected(QString)));
    QObject::connect(&m_client, SIGNAL(errorReceived(QString,QString)), this, SLOT(errorReceived(QString,QString)));
    QObject::connect(&m_client, SIGNAL(heartbeatReceived()), this, SLOT(heartbeatReceived()));
    QObject::connect(&m_client, SIGNAL(messageReceived(QString)), this, SLOT(messageReceived(QString)));
}

EchoClient::~EchoClient()
{
}

void EchoClient::open(QUrl url)
{
    m_client.open(url);
}

void EchoClient::messageReceived(QString message)
{
    qDebug() << "Message Received:" << message;
}

void EchoClient::errorReceived(QString reason, QString advice)
{
    qDebug() << "Error received:" << reason << "(advice" << advice << ")";
}

void EchoClient::ackReceived(int messageId, QJsonArray arguments)
{
    qDebug() << "Ack received for message with id" << messageId << "arguments:" << arguments;
}

void EchoClient::connected(QString endpoint)
{
    qDebug() << "Connected to endpoint" << endpoint;
    m_client.emitMessage("event with 2 arguments",
                         QVariantList() << 1 << QStringLiteral("Hello socket.io,I am Qter"),
                         function(QJsonArray returnValue) {
        qDebug() << "Got reply from event with 2 arguments:" << returnValue;
    });
    m_client.emitMessage("event with a json object",
                         QVariantMap({ {"number", 1}, { QStringLiteral("message"), QStringLiteral("Hello socket.io")}}),
                         function(QJsonArray returnValue) {
        qDebug() << "Got reply from event with a json object:" << returnValue;
    });
    m_client.on("event from server", function(QJsonArray data) {
        qDebug() << "Got event from server with data" << data;
    });
}

void EchoClient::disconnected(QString endpoint)
{
    qDebug() << "Disconnected from endpoint" << endpoint;
}

void EchoClient::heartbeatReceived()
{
    qDebug() << "Received heartbeat";
    m_client.emitMessage("event with a json object",
                         QVariantMap({ {"number", 1}, { QStringLiteral("message"), QStringLiteral("Hello socket.io")}}),
                         function(QJsonArray returnValue) {
        qDebug() << "Got reply from event with a json object:" << returnValue;
    });
}
創建了一個wssocket連接,connect到服務器,同時也向服務器發送了一些數據,connect(QString str);裏面還使用了回調函數,可以拿到服務器給出的應答
再者我們看下nodejs部分
首先需要安裝nodejs模塊
mac osx下面可以使用brew這個包管理工具 類似linux下面的apt工具 windows需要安裝nodejs安裝包
mac 下面 可以直接brew install nodejs,直接可以給你解決各種依賴關係
但是nodejs下面需要使用npm install socket.io 來安裝socket.io模塊
var io = require('socket.io').listen(8001, {
    "log": false,
    "close timeout": 30
});

io.sockets.on('connection', function(socket) {
    socket.emit('news', 1, 'world', function(data) {
        console.log("Message was delivered.");
    });
    socket.on('event with 2 arguments', function(data1, data2,callback) {
        console.log('Received event with arguments:' + data1 + " and " + data2);

        //setTwoarg();
        function setTwoarg()
        {
            if (callback) {
                callback("Okay received your event with 2 arguments");
            }
        }
        setTimeout(setTwoarg,2000);
    });
    socket.on('event with a json object', function(object, callback) {
        console.log('Received event with object:' + JSON.stringify(object));
        if (callback) {
            callback("Okay received your json object.");
        }
    });
    socket.emit("event from server", {"attribute1" : "hello", "attribute2": "world!"});
});
這裏是nodejs代碼
代碼就創建了一個socket.io的服務,socket.on是監聽客戶端的鏈接,而emit是發送數據出去
socket.io接口如何使用可以參考socket.io網站
Qt部分寫好後,在終端運行node server.js 然後客戶端啓動就可以鏈接服務器,做各種操作啦。
各位可以暢遊服務器與客戶端之間
晚安

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章