Giter VIP home page Giter VIP logo

libjson-rpc-cpp's Introduction

I created a new C++17 header only implementation -> json-rpc-cxx.

Master CircleCI codecov

libjson-rpc-cpp

This framework provides cross platform JSON-RPC (remote procedure call) support for C++. It is fully JSON-RPC 2.0 & 1.0 compatible.

libjson-rpc-cpp logo

5 good reasons for using libjson-rpc-cpp in your next RPC project

  • Full JSON-RPC 2.0 & partial JSON-RPC 1.0 client and server Support.
  • jsonrpcstub - a tool that generates stub-classes for your JSON-RPC client and server applications.
  • Ready to use HTTP + TCP server and client to provide simple interfaces for your JSON-RPC application.
  • Cross platform build support for Linux and OS X.
  • Super liberal MIT-License.

Other good reasons to use libjson-rpc-cpp

  • Easy to use cmake cross platform build system.
  • Clean and simple architecture, which makes it easy to extend.
  • Continuously tested under MacOS, and various linux distributions.
  • Automated testing using make test.
  • Useful Examples provided. e.g. XBMC Remote using json-rpc client part and stub generator.
  • The stubgenerator currently supports C++, JavaScript, and Python.

Overview

libjson-rpc-cpp logo

Install the framework

Debian (stretch) and Ubuntu (15.10 or later)

sudo apt-get install libjsonrpccpp-dev libjsonrpccpp-tools

Fedora

sudo dnf install libjson-rpc-cpp-devel libjson-rpc-cpp-tools

Arch Linux

For Arch Linux there is a PKGBUILD provided in the AUR.

sudo aura -A libjson-rpc-cpp

Gentoo Linux

sudo emerge dev-cpp/libjson-rpc-cpp

Mac OS X

For OS X a Brew package is available:

brew install libjson-rpc-cpp

Windows

There is a ready to use compiled package here. Just download execute the installer EXE.

Build from source

Install the dependencies

UNIX

For Debian and Arch GNU/Linux based systems, all dependencies are available via the package manager. For OS X all dependencies are available in Brew

Build

git clone https://github.com/cinemast/libjson-rpc-cpp.git
mkdir -p libjson-rpc-cpp/build
cd libjson-rpc-cpp/build
cmake .. && make
sudo make install
sudo ldconfig          #only required for linux

That's it!

If you are not happy with it, simply uninstall it from your system using (inside the build the directory):

sudo make uninstall

Build options:

Default configuration should be fine for most systems, but here are available compilation flags:

  • -DCOMPILE_TESTS=NO disables unit test suite.
  • -DCOMPILE_STUBGEN=NO disables building the stubgenerator.
  • -DCOMPILE_EXAMPLES=NO disables examples.
  • -DHTTP_SERVER=NO disable the libmicrohttpd webserver.
  • -DHTTP_CLIENT=NO disable the curl client.
  • -DREDIS_SERVER=NO disable the redis server connector.
  • -DREDIS_CLIENT=NO disable the redis client connector.
  • -DUNIX_DOMAIN_SOCKET_SERVER=YES enable the unix domain socket server connector.
  • -DUNIX_DOMAIN_SOCKET_CLIENT=YES enable the unix domain socket client connector.
  • -DFILE_DESCRIPTOR_SERVER=NO disable the file descriptor server connector.
  • -DFILE_DESCRIPTOR_CLIENT=NO disable the file descriptor client connector.
  • -DTCP_SOCKET_SERVER=NO disable the tcp socket server connector.
  • -DTCP_SOCKET_CLIENT=NO disable the tcp socket client connector.

Using the framework

This example will show the most simple way to create a rpc server and client. If you only need the server, ignore step 4. If you only need the client, ignore step 3. You can find all resources of this sample in the src/examples directory of this repository.

Step 1: Writing the specification file

[
	{
		"name": "sayHello",
		"params": {
			"name": "Peter"
		},
		"returns" : "Hello Peter"
	},
	{
		"name" : "notifyServer"
	}
]

The type of a return value or parameter is defined by the literal assigned to it. The generated stubs will will use the "returns" type to validate the response. In this example you can see how to specify methods and notifications.

Step 2: Generate the stubs for client and server

Call jsonrpcstub:

jsonrpcstub spec.json --cpp-server=AbstractStubServer --cpp-client=StubClient
mkdir -p gen
mv abstractstubserver.h gen
mv stubclient.h gen

This generates an AbstractStubServer and a StubClient class and moves them to the gen folder.

Step 3: implement the abstract server stub

Extend the abstract server stub and implement all pure virtual (abstract) methods defined in spec.json.

See src/examples/stubserver.cpp

In the main function the concrete server is instantiated and started. That is all for the server. Any JSON-RPC 2.0 compliant client can now connect to your server.

Compile the server with:

g++ stubserver.cpp -ljsoncpp -lmicrohttpd -ljsonrpccpp-common -ljsonrpccpp-server -o sampleserver

Step 4: Create the client application

See src/examples/stubclient.cpp

Compile the client with:

g++ stubclient.cpp -ljsoncpp -lcurl -ljsonrpccpp-common -ljsonrpccpp-client -o sampleclient

Contributions

Please take a look at CONTRIBUTING.md

You can also donate via Donate

Changelogs

Changelogs can be found here.

API compatibility

We do our best to keep the API/ABI stable, to prevent problems when updating this framework. A compatiblity report can be found here.

License

This framework is licensed under MIT. All of this libraries dependencies are licensed under MIT compatible licenses.

References

If you use this library and find it useful, I would be very pleased if you let me know about it.

libjson-rpc-cpp's People

Contributors

adah1972 avatar akindyakov avatar alexandre-poirot avatar bb111189 avatar bcachet avatar bertrandboudaud avatar bjaraujo avatar cblp avatar chfast avatar cinemast avatar danielkoohmarey avatar debris avatar domob1812 avatar ericlagergren avatar gogo40 avatar ignatenkobrain avatar jdmichaud avatar jmassey-jacques avatar joegen avatar lookfwd avatar mgorny avatar rangatce avatar ruslo avatar se2dev avatar skyfireitdiy avatar smurfy avatar stelcheck avatar vraychev avatar waqar144 avatar zhangyafeikimi 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  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

libjson-rpc-cpp's Issues

JSON Schema for spec

Hi, I'm kinda new to JSON-RPC, but keep reading about it and JSON Schema. They seem like they could really go hand in hand. What is the spec format you are using now? I'm not familiar with it, and it seems like a custom invention.

Have you ever considered using JSON Schema? Alternatively, there is SMD, but that doesn't seem as popular.

How to call a procedure using javascript?

Hi,

I was using the previous libjson-rpc-cpp in my project WGSLib (https://github.com/gogo40/wgslib) and everything was working correctly. My web client (https://github.com/gogo40/wgslib/blob/master/clients/web/js/wgslib/variogram.js) written in javascript was working well.

But, after I updated my library to support the new libjson-rpc-cpp version, my web client isn't working. What's the problem? My server is this one: https://github.com/gogo40/wgslib/blob/master/server/wgslibserver/wgslibserver.h

Thanks in advance.

abstractrequesthandler.h compile error.

I get the follow compile error in a android environment. Is there need a virtual destructor?

abstractrequesthandler.h:15:11: error: 'class jsonrpc::AbstractRequestHandler' has virtual functions and accessible non-virtual destructor [-Werror=non-virtual-dtor]

Named parameters in spec file and request

It seems like the spec file parser never sets the value paramDeclaration in the procedure meaning the server is only able to understand method parameters if passed as an array instead of named args.

If I change the parser so it sets the paramDeclaration value based on how the parameters are declared in the spec file, then it seems like the server is able to accept named parameters, but only if all of the are supplied.

If I have understood the JSON-RPC correctly, it should be perfectly valid to leave out arguments when calling a method with name parameters. These values should then be set to null.

Is this a bug or have I misunderstood something?

I will be happy to look further into this and if possible come with a patch/pull-request.

Thanks.

Websocket implementation

...where both the client and the server talk to one another without reopening a socket per RPC. I couldn't figure this out in 0.2. If it can't yet be done in another way, I'd lobby for supporting WebSockets with the following test case:

https://github.com/Textalk/jquery.jsonrpcclient.js

WebSockets would be excellent because you could authenticate and connect once (both expensive operations) and chat more cheaply thereafter.

BTW, 0.2 works delightfully with a server I made with http://www.gorillatoolkit.org/pkg/rpc/v2 and http://www.gorillatoolkit.org/pkg/rpc/v2/json as long as:

  1. You name the method YourGoStruct.YourExportedMethod in the .json schema file.
  2. You call client->YourGoStruct_YourExportedMethod(...).
  3. You carefully read the generated header to see that the arguments are lexicographically sorted. :-)

Thanks for the great library!

Jeremy

installing socket.h

socketclient.h includes the header socket.h by

include <jsonrpccpp/common/helper/socket.h>

but the installer placed it under
/usr/local/include/jsonrpccpp/common/socket.h

change interpretation to positional params

Hi! By default, application retrieves 'name' field as parameter and I'd like to know how you can change the interpretation of the parameters from 'by param name' to 'by param position'. So I want to change 'json-object' to 'json-array' as parameter.

EDIT:
i'm sending string like this:
{"jsonrpc":"2.0","method":"changes","id":1,"params":["1381908073"]}
and use procedure:
Procedure proc1("changes", PARAMS_BY_POSITION, JSON_STRING, "param1", JSON_STRING, NULL);

and i have such error:
/usr/src/libjson-rpc-cpp/src/jsonrpc/json/json_value.cpp:1065: const Json::Value& Json::Value::operator[](const char*) const: Assertion type_ == nullValue || type_ == object
Value' failed.`

library name clash with json-c -- please rename to libjson-rpc-cpp.so (or similar)

Detected file collision(s):

  /usr/lib/libjson.so

Searching all installed packages for file collisions...

Press Ctrl-C to Stop

dev-libs/json-c-0.10-r1:0::gentoo
/usr/lib/libjson.so

Package 'dev-util/libjson-rpc-cpp-9999' NOT merged due to file
collisions. If necessary, refer to your elog messages for the whole
content of the above message.

Compiling autogenerated code with -Wextra

I prefer to compile me code with the -Wextra option (among others) warnings and it is almost possible with the autogenerated stubs from the jsonrpcstub program.

The only issue is, that if an autogenerated method doesn't accept any parameters, GCC (and possibly others) will warn that "request" is an unused parameter.

I find the "unused parameter" warning fairly useful, so I would prefer to keep that warning.

I have worked around it by adding this->cg.writeLine("(void)request;"); at the start of the function body generation in cppserverstubgenerator.cpp, but I'm not sure this is the nicest solution.

I could also hack around my build scripts to build the stubgenerator with less warnings enabled, but that would be a bit of a shame.

So in short, it seems like the code can almost compile with -Wextra and I personally find it worth the minor effort to make it able to compile cleanly with -Wextra.

Thanks.

On CentOS 6.4, I needed to remove the following file

./src/example/CMakeLists.txt

Even then, I need to cmake && make twice: it fails on the first make with

make[3]: *** No rule to make target `out/libjsonrpc.so.0.2.1', needed by `out/test/errorhandling'. 

Is it possible that I am doing wrong, or is this an issue requiring resolution?

Batch

I believe it is possible with JSON-RPC to batch multiple calls into a single request. Does this library support that, and if so are there any examplea for both client and server side?

Request method without parameters and non-number request id

It seems like the code for validating a request is a bit too strict when it comes to request parameters.

The potentially problematic code is in rpcprotocolserver.cpp in the function RpcProtocolServer::ValidateRequest.

The check request.isMember(KEY_REQUEST_PARAMETERS) which checks if the parameters field is present doesn't seem needed since the spec says:

params
A Structured value that holds the parameter values to be used during the invocation of the method. This member MAY be omitted.

I have tested at least one different JSORPC client implementation that omits the parameter field if there are no parameters to send and have tried simply removing the test which seems to be working fine. If there are no side-effects I haven't spotted, may I suggest simple removing this check?

Additionally, the same validation code also has the check request["id"].isInt() for testing the the ID fields value is an integer. Again, according to the spec:

id
An identifier established by the Client that MUST contain a String, Number, or NULL value if included.

So it is quite explicitly not a requirement that the ID parameter is an integer in order to follow the spec.

I have tried removing this field as well without any problems. As far as I can tell it is simply being sent unmodified back to the caller. Can I suggest removing this check as well?

Thanks a lot!

Compiling Example on Ubuntu Error

In trying to compile the example:
g++ stubserver.cpp -ljsonrpc -o stubserver

I get the following errors:

stubserver.cpp: In constructor ‘MyStubServer::MyStubServer()’:
stubserver.cpp:28:30: error: expected type-specifier before ‘HttpServer’
AbstractMyStubServer(new HttpServer(8080))
^
stubserver.cpp: In function ‘int main()’:
stubserver.cpp:52:13: error: ‘getchar’ was not declared in this scope
getchar();
^
I on Ubuntu 14.04 LTS (Trusty Tahr)
using g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2

Segfault

Segfault if two HTTPConnectors on the same port are started

Header access

My application is using JSON-RPC, but is expecting a header to be present when a user is authenticated. As far as I can see, headers are not accessible at this point. Anything which would stop us from exposing methods to add/remove header entries as required?

Something like (forgive my lack of actual C++ knowledge here):

HttpClient *httpClient = new HttpClient("http://172.16.13.2/game/jsonrpc");
Client c(httpClient);

// Make a first call, authenticate

httpClient->addHeader("X-SESSION-HEADER", res["sessionKey"]);

// Make other calls, now using the session

httpClient->removeHeader("X-SESSION-HEADER");

// All other calls are now unauthenticated

Would that be good/work?

Compile error in mainserver example

On Ubuntu 12.04 64bit, gcc 4.4:

g++ mainserver.cpp -ljsonrpc -o sampleserver
mainserver.cpp: In function ‘int main()’:
mainserver.cpp:33:18: error: cannot declare variable ‘s’ to be of abstract type ‘MyStubServer’
mainserver.cpp:9:7: note: because the following virtual functions are pure within ‘MyStubServer’:
abstractmystubserver.h:38:21: note: virtual int AbstractMyStubServer::addNumbers(const int&, const int&)

License Mongoose

First of all I would like to thank you for your great work!

Regarding the "Issue":
I'm a little bit confused about the License of Mongoose. In your README.md you say that Mongoose is under MIT License. When I follow the link you've provided (https://github.com/cesanta/mongoose) it says that Mongoose is under GPLv2. Can you provide some input on that?

Cannot add optional parameters to the server method

I see such limitation in the lib (may be i miss something).

  1. According to spec: http://www.jsonrpc.org/specification#request_object
    request params may be omitted.
  2. i want to implement method that take optional parameters, - that is the client can omit them in run time. For example method
    GetLog(optional filter1, optional filter2,...).
    So in one run the client can use GetLog(time filter)
    like this
    {"jsonrpc": "2.0", "method": "GetLog", "params": ["2013/12/00:00:00"], "id": 1}
    In the other without any filter (according to the spec this seems to be OK)
    {"jsonrpc": "2.0", "method": "GetLog", "id": 1}

But i don't see how i implement this with the lib (something like c++ overloading).

Number of mongoose worker threads are not configurable through HttpServer

By default mongoose starts 50 worker threads for dispatching HTTP requests that is simply too much for my application and it is just wasting useful resources. Unfortunately I found no option in the HttpServer class to configure the amount of worker threads.

Also created a patch to solve the problem by extending the constructor of HttpServer with an optional numeric parameters indicating how many threads mongoose should start. The patch can be found here: http://minimaldiff.hu/libjson-rpc-cpp-workers.patch

jsonrpcstub will generate notification as callMethod instead of CallNotification

jsonrpcstub tool will generate notification as callMethod instead of CallNotification, so for example having something like:

{
     "notification" : "notifyServer",
     "params": null
}

Like in your example, will generate:

void notifyServer()
{
     Json::Value p;

     this->client->CallMethod("notifyServer",p);
}

With callMethod it doesn't work, it should be:

void notifyServer()
{
    Json::Value p;

    this->client->CallNotification("notifyServer",p);
}

I tried modifying it by hand inside the generated header and the notification worked fine.

So I suppose that the jsonrpcstub tool does not correctly generate the stub if it encounter a notification.

Best Regards,
Giordano

Use the client to perform request on custom json-rpc service

Hi,

I want to make a json-rpc request to betfair.com api, which needs to have two specific headers and use a certificate (crt) file along with a private RSA key (.key)
In python it's as simple as (taken from http://tinyurl.com/n5fo9lp):

import request
payload = 'username=myusername&password=password'
headers = {'X-Application': 'SomeKey', 'Content-Type': 'application/x-www-form-urlencoded'}

resp = requests.post('https://identitysso.betfair.com/api/certlogin', data=payload, 
                                  cert=('client-2048.crt', 'client-2048.key'), headers=headers)

Can I use this library in order to perform such a request?

Thanks,
Stelios

Bidirectional possible from just server

It seems there's no obvious way of creating a server stub that can not only receive but also send messages to the client side.

JSON-RPC 1.0 spec says this is possible through empty POST requests:

"To give the serverside peer a chance to send messages to the client side peer, the client side peer may reopen communication by sending an empty HTTP POST."

I would hope 2.0 doesn't make it explicitly impossible...

Stub generator changes numbers in method names to underscores.

Is there a reason why string StubGenerator::normalizeString(const string &text) changes numbers to underscores? I have browsed through the json spec and didn't see anything that prohibits numbers (although it is certainly possible I missed something).

I found this out when one of my json rpc calls (get100uSDelay) ... changed :)

Furthermore, if this IS intentional, instead of changing the string, should an error be thrown instead or at least a warning message to let people know the output is going to be different than the spec file?

cross-plattform support

are you planning on porting libjson-rpc-cpp to WIN32?
if there`s something that needs to be done a priori - let me know!

SIGSEGV if HTTP request has no Content-Length

curl -X POST 'http://localhost:8080' --data ''
POST / HTTP/1.1
User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8o zlib/1.2.3.3 libidn/1.15
Host: localhost:8080
Accept: */*
Content-Length: 0
Content-Type: application/x-www-form-urlencoded

OK, but

curl -X POST 'http://localhost:8080'
POST / HTTP/1.1
User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8o zlib/1.2.3.3 libidn/1.15
Host: localhost:8080
Accept: */*

Got SIGSEGV, expected error -32700 and running program.

Assert fails when ID member of request is double number

Hi,
i'm using the lib in my project (on arm arch), and saw next crash problem:

  1. The client uses its miliseconds count as the ID of the method request,
    /* for example id
    wget -O- --header 'Content-Type:application/json' --header 'Accept: application/json' http://$IP:8080/remote/json-rpc --post-data '{"jsonrpc":"2.0","id":1373737373737,"method":"SomeRequest" , "params" : [] }'
  2. Because of the some logic problem, the request cannot be performed, so my code throws JsonRpcException
    /* JSON_RPC_APP_ERROR_CODE==-32001 */
    throw jsonrpc::JsonRpcException(JSON_RPC_APP_ERROR_CODE,
    "cannot perform the request...");
  3. The error propagates, and finally come to file errors.cpp and here it fails, because it tries to interpreter ID as integer (this line in next func - error["id"] = request["id"].asInt(); , here it fails )
    JSON_ASSERT_MESSAGE( value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range" );

So to fix the crash i have changed next original function (in file errors.cpp)

Json::Value Errors::GetErrorBlock(const Json::Value& request, const int& errorCode)
{
Json::Value error;
error["jsonrpc"] = "2.0";
error["error"]["code"] = errorCode;
error["error"]["message"] = GetErrorMessage(errorCode);

    if(request["id"].isNull())
    {
        error["id"] = Json::nullValue;
    }
    else
    {
        error["id"] = request["id"].asInt();
    }
    return error;
}

with this one
Json::Value Errors::GetErrorBlock(const Json::Value& request, const int& errorCode)
{
Json::Value error;
error["jsonrpc"] = "2.0";
error["error"]["code"] = errorCode;
error["error"]["message"] = GetErrorMessage(errorCode);

    if(request["id"].isNull())
    {
        error["id"] = Json::nullValue;
    }
    else if (request["id"].isDouble())
    {
      error["id"] = request["id"].asDouble();
    }
    else
    {
        error["id"] = request["id"].asInt();
    }
    return error;
}

And this fixed the run time crash of the lib.

Primitive data types passed by const reference in generated stub functions

The stub generator creates all arguments pass to functions as const references, creating member function signatures like:

std::string foo(const bool& bar);

Which is of course fairly pointless and might actually be less efficient than simply passing by value.

As far as I can tell by looking at cpphelper.cpp it should be fairly easy to change, for instance by distinguishing between return values and input arguments.

I will be happy to throw a patch together if it's any help.

Not a big issue, mostly just hurts the eyes a bit :-)

Thanks.

How to cross compile ?

I want compile with NDK toolchain, but it still compile with g++,not arm-linux-androideabi-g++; Any one may give me some sugestion? I use the follow step;

1.make a toolchain.
export SYSROOT=/opt/ndk/android-ndk-r9d/platforms/android-19/arch-arm
sudo /opt/ndk/android-ndk-r9d/build/tools/make-standalone-toolchain.sh --platform=android-19 --install-dir=/opt/android
2. set env
export PATH=$PATH:/opt/android/bin

export HOST=arm-linux-androideabi
export CPP="${HOST}-gcc"
export STRIP="${HOST}-strip"
export OBJCOPY="${HOST}-objcopy"
export AR="${HOST}-ar"
export RANLIB="${HOST}-ranlib"
export LD="${HOST}-ld"
export OBJDUMP="${HOST}-objdump"
export CC="${HOST}-gcc"
export CXX="${HOST}-g++"
export NM="${HOST}-nm"
export AS="${HOST}-as"
3.complie
autoreconf -if
../configure --host=arm-linux --prefix=/home/cll/programming/c/json_rpc/ndk/libjson-rpc-cpp/build/out
make
make install

missing phtread

I cloned the curent version. set
-DCOMPILE_TESTS=YES
-DCOMPILE_STUBGEN=YES
-DCOMPILE_EXAMPLES=YES
-DHTTP_SERVER_MONGOOSE=NO
-DHTTP_CLIENT_CURL=NO
-DSOCKET_SERVER=YES
-DSOCKET_CLIENT=YES
after cmake . && make I got the error:
Linking CXX executable ../../bin/jsonrpcstub
../../lib/libjsonrpccommon.so.0.3.0: undefined reference to pthread_create' ../../lib/libjsonrpccommon.so.0.3.0: undefined reference topthread_join'

After adding -lpthread in libjson-rpc-cpp/src/stubgenerator/CMakeFiles/jsonrpcstub.dir/link.txt
Linking is successfull

putting server and client in same program

Hi,

I am trying to implement a node which can be bot server and client. And server/client shares some data structures and both can modify them.

What is the right way to use this library to do that? is that possible or not?

thanks.

Makerbot's libjsonrpc.so conflict

Hi!
Today I downloaded the library.
It compile and installed fine, with not errors, as per instructions.

However when I followed the example instructions for compiling a simple client, I got many undefined references.
After verifying I had /usr/local/lib/libjsonrpc.so in the right place, and the symbols, as expected, referenced in the .so file, I found that I had a /usr/lib/libjsonrpc.so.

Later found out that it belongs to the debian package 'mb-libjsonrpc'. Makerbot's JSON-RPC library.

After removing Makerware and its libraries, I was able to compile the client example by myself.

Cheers!

nan and inf

A double value 'nan' is serialized just as "nan" but it should not. JavaScript has no such a literal. Instead, NaN is a valid literal in JavaScript. Although NaN is not valid for JSON, some of other implementations allow NaN (e.g Python https://docs.python.org/2.7/library/json.html). The same applies to +/-inf.

There are some options to handle such values:

  1. raise an exception
  2. convert it to null
  3. serialize as "NaN"/"Infinity"/"-Infinity"

I have a proof-of-concept code that implements the option 3.
https://github.com/knzm/libjson-rpc-cpp/compare/fix-jsonvalue

Compiling under MinGW

Hi,

I can't compile libjson-rpc-cpp 0.2.1 under Windows/ MinGW ;-(
Compiling of the same packet works under Ubuntu. In both cases I create the makefile with 'cmake -G 'Unix Makefile" .. ' and then running make.
With Windows compiling the libs works, but the creation of the examples Code crashes (see errormessage below).

json::HttpClient implements pure virtual method SendMessage(const string&, std::string&) of AbstractClientConnector. There is no pure virtual function anymore!
So after all I can't create an instance of class HttpClient because of that "error". Is it perhaps a known problem? gcc-Version is 4.8.1, libcurl 7.18.0

Andre ;-)

errormessage:

D:/install/cinemast-libjson-rpc-cpp-7e628ac/src/test/errorhandling.cpp: In function 'int main(int, char*)':
D:/install/cinemast-libjson-rpc-cpp-7e628ac/src/test/errorhandling.cpp:59:71: error: cannot allocate an object of abstract type 'jsonrpc::HttpClient'
Client
client = new Client(new HttpClient("http://localhost:8080"));
^
In file included from D:/install/cinemast-libjson-rpc-cpp-7e628ac/src/jsonrpc/rpc.h:20:0,
from D:/install/cinemast-libjson-rpc-cpp-7e628ac/src/test/server.h:13,
from D:/install/cinemast-libjson-rpc-cpp-7e628ac/src/test/errorhandling.cpp:11:
D:/install/cinemast-libjson-rpc-cpp-7e628ac/src/jsonrpc/connectors/httpclient.h:20:11: note: because the following virtual functions are pure within 'jsonrpc::HttpClient': class HttpClient : public AbstractClientConnector
^
In file included from D:/install/cinemast-libjson-rpc-cpp-7e628ac/src/jsonrpc/client.h:13:0,
from D:/install/cinemast-libjson-rpc-cpp-7e628ac/src/jsonrpc/rpc.h:14,
from D:/install/cinemast-libjson-rpc-cpp-7e628ac/src/test/server.h:13,
from D:/install/cinemast-libjson-rpc-cpp-7e628ac/src/test/errorhandling.cpp:11:
D:/install/cinemast-libjson-rpc-cpp-7e628ac/src/jsonrpc/clientconnector.h:29:26: note: virtual void jsonrpc::AbstractClientConnector::SendMessage(const string&
, std::string&)
virtual void SendMessage(const std::string& message, std::string& result) throw(JsonRpcException) = 0;
^
make[2]: *** [src/test/CMakeFiles/errorhandling.dir/errorhandling.cpp.obj] Error 1
make[1]: *** [src/test/CMakeFiles/errorhandling.dir/all] Error 2
make: *** [all] Error 2

Build failure on MacOS

I get the following build error:

Scanning dependencies of target xbmcremote
[100%] Building CXX object src/example/CMakeFiles/xbmcremote.dir/xbmcremote.cpp.o
/Users/dima/build/libjson-rpc-cpp/src/example/xbmcremote.cpp: In function 'int kbhit_mac()':
/Users/dima/build/libjson-rpc-cpp/src/example/xbmcremote.cpp:57:33: error: 'read' was not declared in this scope
         error  = read(0, &ch, 1 );       /* get char from stdin */
                                 ^
make[2]: *** [src/example/CMakeFiles/xbmcremote.dir/xbmcremote.cpp.o] Error 1
make[1]: *** [src/example/CMakeFiles/xbmcremote.dir/all] Error 2
make: *** [all] Error 2

I tried both clang and gcc (from macports).

Missing virtual destructors

The classes AbstractRequestHandler and AbstractServerConnector has (pure) virtual methods, but no virtual destructor.

As you are probably aware this can lead to undefined behavior if a derived instance is destroyed through a pointer or reference to its base class.

It doesn't seem like it is a problem at the moment, but the moment a destructor is added to one of the classes that derive from these classes the behavior will be undefined and therefore (probably) not as expected.

May I suggest adding empty virtual destructors to these classes?

The few clockcycles overhead on destruction are well worth saving the pain of debugging if a destructor is added to a derived class sometime in the future.

It would also mean you could add -Wnon-virtual-dtor to the list of compiler warnings if you like.

In MinGW: can't find curl

As you can see, I have curl installed, but for some reason cmake is having some problems finding it.

/c/Users/Mat/Projects/vatpc/extern/libjson-rpc-cpp/build$ ls /usr/include/curl
curl.h             curlbuild.h.in  easy.h     stdcheaders.h
curlbuild.h        curlrules.h     mprintf.h  typecheck-gcc.h
curlbuild.h.cmake  curlver.h       multi.h

/c/Users/Mat/Projects/vatpc/extern/libjson-rpc-cpp/build$ ls /usr/lib/*curl*
/usr/lib/libcurl.a  /usr/lib/libcurl.def  /usr/lib/libcurldll.a

/c/Users/Mat/Projects/vatpc/extern/libjson-rpc-cpp/build$ ls /usr/bin/*curl*
/usr/bin/curl.exe  /usr/bin/libcurl.dll

/c/Users/Mat/Projects/vatpc/extern/libjson-rpc-cpp/build$ cmake -G "MSYS Makefiles" ..
CMake Error at C:/MinGW/msys/1.0/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:97 (message):
  Could NOT find CURL (missing: CURL_LIBRARY) (found version "7.29.0")
Call Stack (most recent call first):
  C:/MinGW/msys/1.0/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake: 291 (_FPHSA_FAILURE_MESSAGE)
  C:/MinGW/msys/1.0/share/cmake-2.8/Modules/FindCURL.cmake:54 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  lib/jsonrpc/CMakeLists.txt:5 (find_package)

-- Configuring incomplete, errors occurred!

Communicating with bitcoin wallet using json-rpc

I noticed that when I used this library to communicate with the bitcoin wallet I kept getting the following error: Exception -32001 : The response is invalid. Below is the response I got when I send the "getinfo" method to the bitcoin wallet.

Exception -32001 : The response is invalid: {"result":{"version":80300,"protocolversion":70001,"walletversion":60000,"balance":0.00000000,"blocks":64893,"timeoffset":0,"connections":1,"proxy":"","difficulty":23.50125722,"testnet":false,"keypoololdest":1377970991,"keypoolsize":101,"paytxfee":0.00000000,"errors":""},"error":null,"id":1}

Upon examining the response I figured out the bitcoin wallet was not sending "jsonrpc" (KEY_REQUEST_VERSION) back in its response. Thus it was throwing this error. If one goes into the file rpcprotocolclient.cpp one would see the following code on line 78. if(value.isMember(KEY_ID) && (value.isMember(KEY_REQUEST_VERSION) && (value.isMember(KEY_RESULT) || value.isMember(KEY_ERROR)))
Take out the value.isMember(KEY_REQUEST_VERSION) on this line and it will work for communicating with the bitcoin wallet using this library. Maybe I should make the change in the bitcoin wallet instead. I look at it later if I get the time. But anyways anyone wanting to used this library to communicate with the bitcoin wallet will need to make this change.

PS. This is a nice and handy library and thanks for those who took the time and developed it

Matthew G

Remove config usage and replace by explicit method configuration

It is quite inconvenient to use non-optional config file: In any project larger then one file there are a own configuration files and adding one for this lib is not a good idea.

Moreover, there is no need to configure jsonrpc server, because methods provided by the server are fixed.

I suggest to remove usage of config file and replace it by explicit method binding like in jsonrpc-cpp, desirably with usage of standard functors (c++11 std::function) or function-like objects for prior standard (C++03).

sample

class MyApp
{
    std::unique_ptr<Server> _serv;
    void init_jsonrpc()
    {
        _serv.reset( new Server("samplejsonrpcserver", new HttpServer(8080)) );
        serv->add_method( std::bind (MyApp::rpc_method1, this ) );
        serv->add_method( std::bind (MyApp::rpc_method2, this ) );
    }

    void rpc_method2(const Json::Value& request, Json::Value& response){}
    void rpc_method2(const Json::Value& request, Json::Value& response){}

};

Positional params

Is it possible to generate stub with positional, not only named params?
Suppose I want to sum two integers a and b:

[{ "method": "addTwoNumbers", "params": { "a": 5, "b": 4}, "returns": 9}]

And it's fine. Now without names:

[{ "method": "addTwoNumbers", "params": [5, 4], "returns": 9}]

But this returns "Exception -32007 : Procedure specification mallformed"

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.