Giter VIP home page Giter VIP logo

jcon-cpp's People

Contributors

bobvandevijver avatar cculianu avatar chlp avatar dracc avatar fr3nchk1ss avatar holagvk avatar jhihn avatar joncol avatar lightx2 avatar neurocod avatar novikovas avatar positron96 avatar qv-8942 avatar sayezz avatar wsxarcher avatar zeromem88 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jcon-cpp's Issues

Logging/Middle-ware support?

Is their a safe/easy way to go about making logging/middle-ware routes?

P.S great library! We're about to use it in a production setting

Empty json_server_log.txt file

I would like to capture some of the logError messages into a file. Our application, when started, creates a json_server_log.txt file, but nothing is ever placed into it. I have searched for logging level filter values, etc, nor can I find any conditional compilation flags which might be needed to enable logging (although, I would expect if it was disabled, it also would not bother to open a file). (Also tried turning on the DEBUG build type in the CMake generation.) It is (slightly) possible that something in the rest of this large application is interfering somehow with the logging, but I have not found anything that appears suspicious - I thought I'd ask here in case someone else has encountered this. (I have been successfully using JCON-CPP using the TCP transport for some time, but am now trying to change over to using websocket transport). I will add that I'm sending method requests to this server, and it is replying that the method is not found, and I can see in the code where this situation calls logError, so it is not the case that nothing is appearing because nothing is wrong. Thanks.

Batch calls not implemented

Since there's an assertion for the first char of the request to be {, batch calls can't be made.

A batch call is an array of requests. JSON arrays start with [, thus the assertion is hit.

Edit: Sorry, just noticed that it already says so right in the readme. Not less of an issue though.

Track up-/downloadprogress when transmitting files

Hi,
I'm using your library for a Server-Client QT 5.13.1 C++ application. The framework uses TCP as underlying transport layer.
Is there a way to track the current up-/downloadprogress of transmitted files? It would be useful for our users to see the progress, since the up-/download of large files takes a considerable amount of time.

I tried to use the QT functions QTcpSocket::bytesWritten , QTcpSocket::bytesAvailable etc. but they were not providing the correct numbers. The data is encoded as Base64 and stored in a QByteArray.

Do you have any suggestion to achieve the wanted feature?

Thank you for any reply.
Best regards,
Max B.

Cannot build on OSX Yosemite

Using OSX 10.10.5, Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn), CMake 3.5.2, Qt 5.6 (not in PATH).

I am unable to build this project. I've done a lot of hacking on the CMakeLists and have gotten to the point where it actually builds everything, but fails to link due to duplicate symbols such as this one:

duplicate symbol __ZTSN4jcon22JsonRpcWebSocketServerE in:
    src/jcon/CMakeFiles/jcon.dir/jcon_automoc.cpp.o
    src/jcon/CMakeFiles/jcon.dir/moc_json_rpc_websocket_server.cpp.o

The rest look pretty similar, just with various other mangled names. I can post them here if you like, but it's a pretty long list.

This is the diff of my changes to the CMakeLists:

diff --git a/CMakeLists.txt b/CMakeLists.txt
index cff6447..a434c1f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -22,7 +22,7 @@ if(APPLE)
     set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
 endif()

-if(UNIX)
+if(UNIX AND NOT APPLE)
     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -Wno-unused-local-typedefs -Wno-unused-but-set-variable -Wno-unused-variable")
     set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
     set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index ea30fde..1737fd6 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -55,22 +55,6 @@ endif()

 target_link_libraries(${PROJECT_NAME} jcon)

-if(USE_QT)
-  find_package(Qt5Network)
-  find_package(Qt5WebSockets)
-  find_package(Qt5Widgets)
-  find_package(Qt5Test)
-  include_directories(${CMAKE_CURRENT_BINARY_DIR} ${Qt5Network_INCLUDE_DIRS})
-  include_directories(${CMAKE_CURRENT_BINARY_DIR} ${Qt5WebSockets_INCLUDE_DIRS})
-  include_directories(${CMAKE_CURRENT_BINARY_DIR} ${Qt5Widgets_INCLUDE_DIRS})
-  include_directories(${CMAKE_CURRENT_BINARY_DIR} ${Qt5Test_INCLUDE_DIRS})
-  # target_link_libraries(${PROJECT_NAME} ${Qt5Core_LIBRARIES})
-  target_link_libraries(${PROJECT_NAME} Qt5::Network)
-  target_link_libraries(${PROJECT_NAME} Qt5::WebSockets)
-  target_link_libraries(${PROJECT_NAME} Qt5::Widgets)
-  target_link_libraries(${PROJECT_NAME} Qt5::Test)
-endif()
-
 if(APPLE)
   set(APPS "\${CMAKE_INSTALL_PREFIX}/bin/${PROJECT_NAME}")

@@ -127,3 +111,4 @@ if(WIN32)
 endif()

 add_subdirectory(jcon)
+
diff --git a/src/jcon/CMakeLists.txt b/src/jcon/CMakeLists.txt
index 2e864f5..03c2386 100644
--- a/src/jcon/CMakeLists.txt
+++ b/src/jcon/CMakeLists.txt
@@ -7,6 +7,11 @@ add_definitions(-DJCON_DLL -DJCON_DLL_EXPORTS)

 add_library(${PROJECT_NAME} SHARED ${${PROJECT_NAME}_headers} ${${PROJECT_NAME}_sources})

+if(USE_QT)
+  find_package(Qt5Core)
+  qt5_use_modules(${PROJECT_NAME} Core Network WebSockets Widgets Test)
+endif()
+
 install(TARGETS ${PROJECT_NAME}
         RUNTIME DESTINATION bin
         LIBRARY DESTINATION lib

Rationale:

  • Clang doesn't recognize the flags: -Wno-unused-local-typedefs -Wno-unused-but-set-variable
    • This means I'm not building with the -Wno-unused-variable flag either. If I add that, I get build errors. I can post those if desired.
  • Your method of finding the Qt packages requires me to specify the path to each module's cmake config separately. My method picks them all up just by pointing cmake to Qt5Core. It's also a lot more concise.
  • It was necessary to move the Qt5 concerns to src/jcon/CMakeLists.txt since the library in src/jcon uses Qt5, but was not being built against it so things like #include <QString> didn't work.

How to connect URL like "ws://localhost:6800/jsonrpc"

In JsonRpcWebSocketClient,I only found the connect api is connectToServer which use host and port as connect parameter,but how can I connect a websocket server with address like "ws://localhost:6800/jsonrpc"?

How to pass client's IP to tcp server?

Hi
First thanks for this great project!
What I want to know is, when use the tcp server mode, is there's a simple way to pass the client's IP to server such as the ExampleService in the README?

Thank you for any reply.

Support for the "event" messages over JSON-RPC.

Hi!
Is there a way to support the "event" type messages by this library? After receiving an event I'd like to send a signal with the content of the message, catch it in my own class and then parse it. For now I added some code in JsonRpcClient::jsonResponseReceived for letting the "event" messages go, but after that when I try to send some request over call() method the library gets stuck inside my added code and then the app crashes.

Please help me :)
Piotr

This is the code I added. The receivedEvent() signal is added to the class.

void JsonRpcClient::jsonResponseReceived(const QJsonObject response)
{
    //qDebug() << "Message received:" << response;
    //JCON_ASSERT(response["jsonrpc"].toString() == "2.0");

    if(response.contains(QString("event"))){
        qDebug() << "Event: " << response;
        emit receivedEvent(response);
        return;
    }

    if (response.value("jsonrpc").toString() != "2.0") {
      . . .

QObject methods are exposed to the server

Hi!
I've found the security issue in the library. Client is able to call QObject methods via RPC, e.g. deleteLater, destroyed, objectNameChanged and _q_registerTimers.

The same thing happens for all signals and slots defined in the object, but it's not a big problem as I can control the logic of these methods.

error: 'auto' not allowed in lambda parameter

Hello!

I am getting this error in json_rpc_server.cpp: error: 'auto' not allowed in lambda parameter

in method:
QString logInvoke(const QMetaMethod& meta_method,
const QVariantList& args,
const QVariant& return_value)
{
const auto ns = meta_method.parameterNames();
auto ps = jcon::variantListToStringList(args);
QStringList args_sl;
std::transform(ns.begin(), ns.end(), ps.begin(),
std::back_inserter(args_sl),
[](auto x, auto y) -> QString {
return static_cast(x) + ": " + y;
}
);

auto msg = QString("%1 invoked ")
    .arg(static_cast<QString>(meta_method.name()));

if (args_sl.empty()) {
    msg += "without arguments";
} else {
    msg += QString("with argument%1: %2")
        .arg(args_sl.size() == 1 ? "" : "s")
        .arg(args_sl.join(", "));
}

if (return_value.isValid()) {
    msg += " -> returning: " + jcon::variantToString(return_value);
}

return msg;

}

not sure why?

best regards

compatibility with other clients

Hi,
I have tried many clients (javascript) and I am unable to use it with http transport.
so I tried with curl.

curl -X POST -H 'Accept:application/json' -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":"12","method":"getRandomInt","params":[12]}' http://localhost:6003

unfortunately it does not reply (I checked with wireshark) ....so, I suppose there may be some compatibility issues , or I missed something ?

server's response may be not processed, because lagged signal binding?

code from main.cpp:

    auto req = rpc_client->callAsync("getRandomInt", 10);

    req->connect(req.get(), &jcon::JsonRpcRequest::result,
                 [](const QVariant& result) {
                     qDebug() << "result of asynchronous RPC call:" << result;
                 });

    req->connect(req.get(), &jcon::JsonRpcRequest::error,
                 [](int code, const QString& message) {
                     qDebug() << "RPC error:" << message
                              << " (" << code << ")";
                 });

Is there possibility that rpc_client->callAsync is called:
auto req = rpc_client->callAsync("getRandomInt", 10);

then date is send to server, server reponse is received, jcon::JsonRpcRequest::result signal is emitted, until then, req->connect is called:

    req->connect(req.get(), &jcon::JsonRpcRequest::result,
                 [](const QVariant& result) {
                     qDebug() << "result of asynchronous RPC call:" << result;
                 });

in multi threading environment, this may happen in theory, and we will not catch the jcon::JsonRpcRequest::result signal at all, and server's response may be not processed, right?

Can not use customized struct type

Hi, I define a customized struct type, and use it as return type of a function in services class.
struct my_info { QString name; };
I used Q_DECLARE_METATYPE and qRegisterMetaType to register the type.
However, I found that the function JsonRpcServer::createResponse failed because
return_value.type() == QVariant::UserType is not well handled.

Could you fix this?

Error: JSON RPC client error: key/value is undefined

I try to receive notifications on client side. I have no control over the server and can only implement the client.
I am using your client example with notifications enabled.

The server from a different application sends this notification (I checked it via Wireshark):
{"jsonrpc":"2.0","method":"methodName","params":{"param1":"data"}}

When listening with your client I get the notification
Error: JSON RPC client error: key/value is undefined

I tried to test it by using your server to recreate the issue. When using your server this is what I see in Wireshark:
{"jsonrpc":"2.0","key":"methodName","value":{"param1":"data"}}

So the server against whom I develop does send method/params while your server sends key/value

  1. How do I send with your server method/params?
  2. What do I need to do on client side so I can receive method/params notifications

Best Regards
say

QtCreator integration

Hi,
It's a Qt based library but it had no QtCreator integration (pro files). Thanks to QtCreator, I could easily spot some compilers warnings, which I corrected.

Also I used Wireshark on my personal project and spotted a bug/feature. When calling a remote procedure with no parameter, the client was sending an empty parameters list instead of nothing. Now it does not send any useless empty list.

I created a pull request.

how to build it?

excuse me ?
how to build it on windows with cmake ?
thank you very much!!!!
I use cmake-gui to generate makfile but when i make it. It seems can not find qt *.a such as below....

[ 4%] Built target jcon_autogen
[ 8%] Linking CXX shared library libjcon.dll
CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x25b): undefined reference to _imp___ZNK11QObjectData17dynamicMetaObjectEv' CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x2a8): undefined reference to _imp___ZN7QObject11qt_metacastEPKc'
CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x2d9): undefined reference to _imp___ZN7QObject11qt_metacallEN11QMetaObject4CallEiPPv' CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x39d): undefined reference to _imp___ZN11QMetaObject8activateEP7QObjectPKS_iPPv'
CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x3eb): undefined reference to _imp___ZN11QMetaObject8activateEP7QObjectPKS_iPPv' CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x44e): undefined reference to _imp___ZN11QMetaObject8activateEP7QObjectPKS_iPPv'
CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x73d): undefined reference to _imp___ZNK11QObjectData17dynamicMetaObjectEv' CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x78a): undefined reference to _imp___ZN7QObject11qt_metacastEPKc'
CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x7bb): undefined reference to _imp___ZN7QObject11qt_metacallEN11QMetaObject4CallEiPPv' CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x894): undefined reference to _imp___ZN11QMetaObject8activateEP7QObjectPKS_iPPv'
CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x8e3): undefined reference to _imp___ZN11QMetaObject8activateEP7QObjectPKS_iPPv' CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x931): undefined reference to _imp___ZN11QMetaObject8activateEP7QObjectPKS_iPPv'
CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cpp:(.text+0x994): undefined reference to `_imp___ZN11QMetaObject8activateEP7QObjectPKS_iPPv'
CMakeFiles\jcon.dir/objects.a(mocs_compilation.obj):mocs_compilation.cp

...............

akeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text+0xd): undefined reference to _imp___ZNK8QVariant4typeEv' CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text+0x55): undefined reference to _imp___ZNK8QVariant6toListEv'
CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text+0xcd): undefined reference to _imp___ZNK8QVariant4typeEv' CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text+0x115): undefined reference to _imp___ZNK8QVariant5toMapEv'
CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text+0x1a1): undefined reference to _imp___ZNK8QVariant8toStringEv' CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text+0x399): undefined reference to _imp___ZN8QVariantD1Ev'
CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text+0x3a5): undefined reference to _imp___ZN8QVariantD1Ev' CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text+0x3e6): undefined reference to _imp___ZN8QVariantD1Ev'
CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text+0x3f6): undefined reference to _imp___ZN8QVariantD1Ev' CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text$_ZN5QListI7QStringEC1Ev[__ZN5QListI7QStringEC1Ev]+0x18): undefined reference to _imp___ZN9QListData11shared_nullE'
CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text$_ZNK8QVariant10canConvertI7QStringEEbv[__ZNK8QVariant10canConvertI7QStringEEbv]+0x19): undefined reference to _imp___ZNK8QVariant10canConvertEi' CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text$_ZN5QListI7QStringE7reserveEi[__ZN5QListI7QStringE7reserveEi]+0x47): undefined reference to _imp___ZN9QListData7reallocEi'
CMakeFiles\jcon.dir/objects.a(string_util.obj):string_util.cpp:(.text$_ZNK8QMapNodeI7QString8QVariantE8nextNodeEv[__ZNK8QMapNodeI7QString8QVariantE8nextNodeEv]+0xf): undefined reference to `_imp___ZNK12QMapNodeBase8nextNodeEv'
collect2.exe: 错误:ld 返回 1
jcon\CMakeFiles\jcon.dir\build.make:364: recipe for target 'jcon/libjcon.dll' failed
mingw32-make[2]: *** [jcon/libjcon.dll] Error 1
CMakeFiles\Makefile2:171: recipe for target 'jcon/CMakeFiles/jcon.dir/all' failed
mingw32-make[1]: *** [jcon/CMakeFiles/jcon.dir/all] Error 2
Makefile:148: recipe for target 'all' failed
mingw32-make: *** [all] Error 2

My cmakelists is

project(jcon)

set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)

file(GLOB ${PROJECT_NAME}_headers *.h)
file(GLOB ${PROJECT_NAME}_sources *.cpp)

add_definitions(-DJCON_DLL)

add_library(${PROJECT_NAME} SHARED ${${PROJECT_NAME}_headers} ${${PROJECT_NAME}_sources})
set_target_properties(${PROJECT_NAME} PROPERTIES PUBLIC_HEADER "${${PROJECT_NAME}_headers}")

find_package(Qt5 COMPONENTS Core Network WebSockets REQUIRED)
target_link_libraries(${PROJECT_NAME} Qt5::Core Qt5::Network Qt5::WebSockets)

install(TARGETS ${PROJECT_NAME}
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib
PUBLIC_HEADER DESTINATION include/jcon
ARCHIVE DESTINATION lib/static)

can anyone help me?? thank you very much!!!!!

Assertion `buf[0] == '{'' failed.

What means this?

json_rpc_endpoint.cpp:139: QByteArray jcon::JsonRpcEndpoint::processBuffer(const QByteArray&, QObject*): Assertion `buf[0] == '{'' failed.

My code:

    auto rpc_client = new jcon::JsonRpcTcpClient(this);

    rpc_client->connectToServer("127.0.0.1", 8555);

    auto result = rpc_client->call("getbalance", "");

    if (result->isSuccess()) {
        QVariant res = result->result();
    } else {
        QString err_str = result->toString();
    }

Is it safe to use QTime?

Hi,

In this method, we use QTime as a timer:

bool JsonRpcWebSocket::waitForConnected(int msecs)
{
    QTime timer(0, 0, 0, msecs);
    bool isConnected = false;
    QObject guard;
    connect(m_socket, &QWebSocket::connected,
            &guard, [&isConnected]() {
                        isConnected = true;
                    });
    timer.start();
    while (!isConnected && timer.elapsed() < msecs) {
        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
    }
    return isConnected;
}

However, from https://doc.qt.io/qt-5/qtime-obsolete.html#elapsed (obsoleted now but nevertheless):

Warning: If the system's clock setting has been changed since the last time start() or restart() was called, the result is undefined. This can happen when daylight-saving time is turned on or off.

So, if I somehow manage to change the system clock while waitForConnected is in-progress, the result will be undefined. Right?

Will you accept a pull request if I change QTime to QElapsedTimer?

Timeout problem in Debug version

I Build JsonRPC on windows 10, with visual studio 2015 in debug mode. I write an Unamanged c++ dll (sdk.dll) that use JsonRpc client to cumminication with another application (Ar.exe) that run JsonRpc server.
So the sdk.dll depends on jcon.dll.
The I copy both sdk.dll and jcon.dll to my test application exe file.
When I call function F from sdk.dll that use JsonRpc to cumminicate with JsonRpce Server in Ar.exe, the remote function on JsonRpc server side called, but the client side not recieve any response and wait until timeout.

P.S: I atteched the build jcon.dll on debug mode.
jcon.zip

tcp client disconnection

Hi,
Using a tcp rpc client connection there seems being a disconnection after a while, if we don't send commands.

the call() replies with not connected

Is there an automatic disconnect ? That was the first problem.

I have tried using jcon client with many python json tcp servers. unfortunately most of them are not able to reliably communicate with jcon !!!!!

Finally I found this working API : https://github.com/joshmarshall/jsonrpctcp

It works , BUT... It is not possible to send 2 calls without disconnecting the client from the server and initiating a new connection.

The code for client side is :

int main(int argc, char* argv[])
{
    QCoreApplication app(argc, argv);

    {
        auto rpc_client = startClient(&app, SocketType::tcp);
	auto result = rpc_client->call("AppendProd","Production",1,32);
        if (result->isSuccess()) {
           qDebug() << "result of synchronous RPC call:" << result->result();
       } else {
         qDebug() << "RPC error:" << result->toString();
      }  
       result = rpc_client->call("AppendProd","Prduction",1,325);
      if (result->isSuccess()) {
        qDebug() << "result of synchronous RPC call:" << result->result();
       } else {
        qDebug() << "RPC error:" << result->toString();
      }

    }
}

the python code for server side is :

from jsonrpctcp.server import Server
from jsonrpctcp import config
from jsonrpctcp import logger
import thread,threading

def AppendProd(type_,m,n):
    print "type",type_,m,n
    return ("Hello",10,11,12,True)

server=Server(('localhost',6002))

import logging
config.verbose = True
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
       

server.add_handler(AppendProd)
server_thread = threading.Thread(target=server.serve)
server_thread.daemon = True
server_thread.start()

import time
while True:
    time.sleep(0.5)

What is the way to log on the jconcpp side ? There is a jcon_client_log.txt file generated, but is empty !

Services namespaces, performance improvements

Hi there!
Thank you for this library! I'm vey happy to use it in my project, but it requires a few small improvements which will slightly simplify implementation of bigger APIs.

It would be worth adding some kind of namespacing system for registered services. At this moment it's not possible to register two services which have two methods with the same name. The best solution would be to rename registerServices method to registerService and introduce additional argument called "namespace", e.g. registerService("MyApiNamespace", servicePointer). Then registered method names will be like MyApiNamespace/methodName. By default, separator may be "/" but it would be nice if it could be configurable (like setSeparator method).

I've also noticed that each time a method is called, the server iterates over all services and methods in order to find a method with a specific name, which means O(n) execution time. imo it'll be better to introduce methods mapping which would reduce execution time to O(1).

Thank you!

no answer from server on really fast computers

Hi,
I had a client (python) / server (jcon) program running fine in a windows 7 computer.

I launched the same program on a really fast computer (3Ghz) and the requests are not seen from the server side .
The socket is connected, but there is no answer from server when making client requests.

What could be the problem ?

server and client both in one program?

Hello Jonas,
I've got a program where we were successfully using your RpcTcpServer code to process JSON RPC requests from another program. I am now trying to add a client to this program, which will make RPC calls to another server. Early on, the program fails in json_rpc_endpoint.cpp at the
JCON_ASSERT(buf[0] == '{'); line, probably before any RPC request has been sent.
(This is on a Mac).
I'll continue debugging, but I thought I'd ask if this is a known problem here (perhaps that, due to buffer reuse, you cannot have a client and server simultaneously in the same program, though I haven't seen anything suspicious like that, yet)?
Thanks,
Andy S.

HOW I USE JCON

Hi i tried to used the jcon rpc-json client and i dont have idea of this work, auto rpc_client = new jcon::JsonRpcTcpClient(parent);, what i need to include inside the file for this...

using the same service on 2 protocols

For technical reasons, I would like to use the same service with two different procols
one with tcp (for python2 clients, where I don't have any json rpc websocket available)
and one with websocket , for web application .
I used different port for the tcp and websocket service

unfortunately, this does not seem to work, I can not work with the websocket service, but the tcp service is ok

I know I have to setup some mutexes in service, if I want to share the same fonctions between the two protocols.

here is my server code :

#include "ControlerServiceApi.h"
#include <jcon/json_rpc_tcp_server.h>
#include <jcon/json_rpc_websocket_server.h>
#include "jcon/json_rpc_file_logger.h"
#include <QCoreApplication>
#include <QUrl>

#include <ctime>
#include <iostream>
#include <memory>
#include <unistd.h>

ControlerService *service;

enum class SocketType {tcp, websocket};

jcon::JsonRpcServer* startServer(QObject* parent,
                                 SocketType socket_type = SocketType::tcp)
{
    int port;
    jcon::JsonRpcServer* rpc_server;
    if (socket_type == SocketType::tcp) {
        qDebug() << "Creating TCP server";
        auto logger = std::make_shared<jcon::JsonRpcFileLogger>("e:\\rpc_log.txt");
        rpc_server = new jcon::JsonRpcTcpServer(parent, logger);
        port = 6004;
    } else {
        qDebug() << "Creating WebSocket server";
        rpc_server = new jcon::JsonRpcWebSocketServer(parent);
        port = 6003;
    }
    rpc_server->registerServices({ service });
    rpc_server->listen(port);
    return rpc_server;
}



int main(int argc, char* argv[])
{

    QCoreApplication app(argc, argv);

    service = new ControlerService();

    auto server1 = startServer(nullptr, SocketType::websocket);
    // pour compatibilité python2, obligé de garder l acces en mode socket tcp
    auto server2 = startServer(nullptr, SocketType::tcp);

#ifdef _WIN32
	{
		std::string path;
        path.assign(tmpdir());
		path += "\\controler_service_ok";
		touch(path.c_str());
	}
#else
	int ret  __attribute__((unused))=system("touch /tmp/controler_service_ok");
#endif
    app.exec(); // <- here 
    delete server1;
    delete server2;
}

Error cmake

Hello,

I would like to include json rpc to my project.
I tried to build with your library but I got error on cmake

Could not find a package configuration file provided by "Qt5WebSockets"
  with any of the following names:

    Qt5WebSocketsConfig.cmake
    qt5websockets-config.cmake

  Add the installation prefix of "Qt5WebSockets" to CMAKE_PREFIX_PATH or set
  "Qt5WebSockets_DIR" to a directory containing one of the above files.  If
  "Qt5WebSockets" provides a separate development package or SDK, be sure it
  has been installed.
Call Stack (most recent call first):
  CMakeLists.txt:53 (qt5_use_modules)


CMake Error at /usr/lib/x86_64-linux-gnu/cmake/Qt5Core/Qt5CoreMacros.cmake:327 (message):
  Can not use "WebSockets" module which has not yet been found.
Call Stack (most recent call first):
  CMakeLists.txt:53 (qt5_use_modules)


CMake Warning (dev) in CMakeLists.txt:
  No cmake_minimum_required command is present.  A line of code such as

    cmake_minimum_required(VERSION 3.5)

  should be added at the top of the file.  The version specified may be lower
  if you wish to support older CMake versions for this project.  For more
  information run "cmake --help-policy CMP0000".
This warning is for project developers.  Use -Wno-dev to suppress it.

-- Configuring incomplete, errors occurred!
See also "/home/contiapps/jcon-cpp/src/build/CMakeFiles/CMakeOutput.log".

I don't understand the problem, can you please help me ? Thanks

push_back error

First - thanks for the amazing library!

I've copied the example files almost exactly (just changed the names slightly), but when i try to register my service, i get this error:

include "jsonrpc_service.h"

include <jcon/json_rpc_file_logger.h>

include <jcon/json_rpc_tcp_client.h>

include <jcon/json_rpc_tcp_server.h>

/* in main.cpp /
void start_jsonrpc_server(QObject
parent)
{
auto rpc_server = new jcon::JsonRpcTcpServer(parent);
rpc_server->registerServices(new JSONRPCService()); /* says Service - singular - in example */
rpc_server->listen(6002);
}

../../ac-player/src/jcon/json_rpc_server.h:103: error: no matching member function for call to 'push_back'
m_services.push_back(std::move(s));
~~~~~~~~~~~^~~~~~~~~

Also worth nothing that using:
rpc_server->registerServices(std::move(std::make_unique()));

Comes back that make_unique is not a recognised function in C++11.

standalone server quits

I modified the example service to have only the server available.
Unfortunately the application will quit.
What can I do to wait for infinite and not quit ?

Javascript compatibility issue

one of my client is a typescript rpc websocket client using rpc-websockets api.

Using common types like int works. Unfortunately, if the function returns QString I have no answer.

What can I do to allow strings to be returned ?

sample ts code

import { Client }  from 'rpc-websockets';
var ws = new Client('ws://localhost:6003')
     
 ws.on('open', function() {
      ws.call('getRandomInt', [20]).then(function(result) {
        console.log("result : ");
        console.log(result);
      })     
});

RPC client throws an exception?

In jcon-cpp/src/jcon/json_rpc_client.cpp:

throw std::runtime_error(msg.toStdString());

It sounds a bit strange, because this is totally un-documented and the rest of the lib does not use exceptions. May be a feature though.

Could I send json to a server with a client ?

Hello,

I would like to send a json with my Qt application to a python server and then retrieve information from the same server.

I did a unit test where I could easily retrieve information but I don't see any example of how to send information.

Sincerely, thank you in advance for your answer

C2491 error

Error C2491 'jcon::JsonRpcTcpClient::staticMetaObject': definition of dllimport static data member not allowed \jcon-cpp\src\jcon\Release\moc_json_rpc_tcp_client.cpp 66

I get this error when compiling the project converted by VS Qt tools, any help?

Server side notification sending.

Hi,

I am newly aware of this component and very interested in.

I succeeded to use this component as a server.
The client part is done with nodeJS web application, using 'simple-jsonrpc-js' at (https://github.com/jershell/simple-jsonrpc-js).

Unfortunately I did find the right way to send asynchronous notifications to web client.
I thought the JSON RPC 2.0 specification allowed this.

Did I miss something?
Should I use low level client APIs to do so?

Happy to hear you soon with pieces of answers.
Regards,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.