enwi / dartzmq

A simple dart zeromq implementation/wrapper around the libzmq C++ library
https://pub.dev/documentation/dartzmq/latest/
MIT License
26 stars 17 forks source link

Question: How to receive string message with subscription? #16

Closed alexanderwwagner closed 1 year ago

alexanderwwagner commented 1 year ago

Question At the moment I try to use your library for a pub/sub setup. I try to get string messages of my python publisher. If I try to write a subscriber with your dart library I have problems to get out the message as string. I tried your provided example too. But there I have the same problem... I do not get the string message, instead of a string I get some ZFrame... Can you help me with my problem? (Look at "To Reproduce") Thank you!

Setup with python publisher and subscriber: Publisher:

import zmq
import random
import sys
import time

port = "6555"
if len(sys.argv) > 1:
    port = sys.argv[1]
    int(port)

context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:%s" % port)

while True:
    # Receives a string format message
    socket.send_string("ML hello")
    time.sleep(1)

Subscriber:

# simple_sub.py
import zmq

host = "127.0.0.1"
port = "6555"

# Creates a socket instance
context = zmq.Context()
socket = context.socket(zmq.SUB)

# Connects to a bound socket
socket.connect("tcp://{}:{}".format(host, port))

# Subscribes to all topics
socket.subscribe("ML")

while True:
    # Receives a string format message
    whole_message = socket.recv_string()
    topic, actual_message = whole_message.split(" ")
    print(actual_message)

Environment OS: Archlinux 6.0.12-arch1-1 Android x86 emulator: Pixel 5 API 30 flutter: 3.3.9 compileSdkVersion 33 ndkVersion flutter.ndkVersion

To Reproduce Subscriber with dart:

    // Tst
    final ZContext context = ZContext();
    final ZSocket socket = context.createSocket(SocketType.sub);
    late StreamSubscription _subscription;
    socket.connect("tcp://192.168.178.26:6555");
    socket.subscribe("ML");

    _subscription = socket.messages.listen((message) {
      print(message.toString());
    });

Output:

I/flutter (31175): ZMessage[ZFrame[[77, 76, 32, 104, 101, 108, 108, 111]]]

enwi commented 1 year ago

Hey @alexanderwwagner ZMessages are made up of one or more ZFrames, which in turn are UInt8Lists containing the payload. To turn the payload back into a string use UTF8.decode(message.first.payload). For further info just take a look at the code documentation 🙂

alexanderwwagner commented 1 year ago

Hey enwi, UTF8.decode(message.first.payload) works, thank you! But can you specify which code documentation you mean? I have not found any example or something else to get it working... Maybe I searched on the wrong place...

enwi commented 1 year ago

Glad that it works 🙂

I meant the code itself. All classes and functions should be documented inside the code base.

enwi commented 1 year ago

You can also find the latest version here