MessagePack-Try to link Java and Python with RPC

Preface

Experimented with the need to integrate a system made with Java and Python, and to make it easy to operate a system implemented with Java with a Python script. At first, I was wondering if I would decide the protocol myself, but MessagePack-RPC seemed to be very convenient, so I decided to go with it.

What I tried

The point is that I want to call the method on the Java side from Python and the method on the Python side from Java. Of course, you have to be able to handle arguments and return values. So, this time,

--If you pass a string, you will get a character with Hello returned (hello) --Pass two arguments and get the sum of them returned (add) --Pass an array of numbers and get the total value returned (sum) --Pass an array of numbers and have it return a line graph image created by matplotlib (make_graph)

I will try it. The server side is Python and the client side is Java.

code

Python side code

server.py


import msgpackrpc
import matplotlib.pyplot as plt
from PIL import Image

class TestServer(object):

    def hello(self, mesg):
        print(mesg)
        return ("Hello, " + mesg.decode()).encode()

    def add(self, a, b):
        return a + b

    def sum(self, d):
        return sum(d)

    def make_graph(self, d):
        plt.plot(d)
        plt.savefig('hoge.png')
        f = open('hoge.png', 'rb')
        d = f.read()
        f.close()
        return d

server = msgpackrpc.Server(TestServer())
server.listen(msgpackrpc.Address("localhost", 1985))
server.start()

Java side code

TestClient.java


import org.msgpack.rpc.Client;
import org.msgpack.rpc.loop.EventLoop;
import org.msgpack.type.Value;

import java.io.*;
import java.util.*;
import java.awt.image.*;
import javax.swing.*;
import javax.imageio.*;

public class TestClient {

    public static void main(String[] args) throws Exception {

        EventLoop loop = EventLoop.defaultEventLoop();
        Client client = new Client("localhost", 1985, loop);
                int v;

        System.out.println(" --- hello ---");
        Value result = client.callApply("hello", new Object[]{"miyo"});
        System.out.println("Result type:" + result.getType());
        String s = new String(result.asRawValue().getByteArray());
        System.out.println(s); // Hello, miyo
        System.out.println();

        System.out.println(" --- add --- ");
        result = client.callApply("add", new Object[]{100, 10}); // 110
        System.out.println("Result type:" + result.getType());
        v = result.asIntegerValue().getInt();
        System.out.println("result = " + v + " :" + (v == 110));
        System.out.println();

        System.out.println(" --- sum --- ");
        result = client.callApply("sum", new Object[]{new int[]{1, 2, 3, 4, 5}}); // 15
        System.out.println("Result type:" + result.getType());
        v = result.asIntegerValue().getInt();
        System.out.println("result = " + v + " :" + (v == 15));
        System.out.println();

        System.out.println(" --- make graph ---");
        result = client.callApply("make_graph",
                                  new Object[]{new int[]{1,2,4,8,10,3,6,8,9,-1}});
        System.out.println("Result type: " + result.getType());
        byte[] raw = result.asRawValue().getByteArray();
        BufferedImage img = ImageIO.read(new ByteArrayInputStream(raw));
        System.out.println(img);
        Icon icon = new ImageIcon(img);
        JOptionPane.showMessageDialog(null,
                                      "",
                                      "image",
                                      JOptionPane.PLAIN_MESSAGE,
                                      icon);
        client.close();
        loop.shutdown();
    }
}

Execution result

The state of the executed terminal looks like this result_console.PNG

I was able to display the graph generated by Python properly result_graph.PNG

so

No, it's convenient !!

reference

I didn't make a note because I used it as a reference ...

Recommended Posts

MessagePack-Try to link Java and Python with RPC
Link to get started with python
Fractal to make and play with Python
Scraping tabelog with python and outputting to CSV
Strategy on how to monetize with Python Java
Procedure to load MNIST with python and output to png
I want to handle optimization with python and cplex
Benchmark for C, Java and Python with prime factorization
Try to operate DB with Python and visualize with d3
Investigate Java and python data exchange with Apache Arrow
Something to enjoy with Prim Pro (X-Play) and Python
Programming with Python and Tkinter
Connect to BigQuery with Python
Encryption and decryption with Python
Python and hardware-Using RS232C with Python-
Connect to Wikipedia with Python
Post to slack with Python 3
I compared Java and Python!
Switch python to 2.7 with alternatives
Write to csv with Python
python with pyenv and venv
Works with Python and R
Easy to use Nifty Cloud API with botocore and python
screen and split screen with python and ssh login to remote server
[Python] How to play with class variables with decorator and metaclass
[pyqtgraph] Add region to the graph and link it with the graph region
Send experiment results (text and images) to slack with Python
Solving with Ruby, Perl, Java and Python AtCoder ATC 002 A
Try to link iTunes and Hue collection case with MQTT
Try to bring up a subwindow with PyQt5 and Python
How to do Bulk Update with PyMySQL and notes [Python]
[Let's play with Python] Image processing to monochrome and dots
Solving with Ruby, Perl, Java and Python AtCoder ATC 002 B
I tried to enumerate the differences between java and python
Convert video to black and white with ffmpeg + python + opencv
I tried to make GUI tic-tac-toe with Python and Tkinter
Get additional data to LDAP with python (Writer and Reader)
How to log in to AtCoder with Python and submit automatically
How to parse Java source code with AST (Abstract Syntax Tree) using ANTLR and Python
Communicate with FX-5204PS with Python and PyUSB
Shining life with Python and OpenCV
solver> Link> Solve Excel Solver with python
Difference between java and python (memo)
Python: How to use async with
Robot running with Arduino and python
Python 3.6 on Windows ... and to Xamarin.
Install Python 2.7.9 and Python 3.4.x with pip.
Java and Python basic grammar comparison
Neural network with OpenCV 3 and Python 3
AM modulation and demodulation with python
[Python] font family and font with matplotlib
[Introduction to Python3 Day 1] Programming and Python
Scraping with Node, Ruby and Python
[Python] Write to csv file with Python
Create folders from '01' to '12' with python
Nice to meet you with python
Scraping with Python, Selenium and Chromedriver
Try to operate Facebook with Python
Output to csv file with Python
Scraping with Python and Beautiful Soup
Convert list to DataFrame with python