Skip to content

Basic Service Example

Jeremy Barlow edited this page Mar 27, 2018 · 5 revisions

This sample demonstrates how to register a DXL service to receive Request messages and send Response messages back to an invoking DxlClient.

The code for the sample is broken into two main sections.

Register service

The first section is responsible for creating a RequestCallback that will be invoked for a specific topic associated with the service. The callback will send back a Response message with a payload of pong for any Request messages that are received.

It then creates a ServiceRegistrationInfo instance and registers the request callback with it via the ServiceRegistrationInfo.add_topic() method.

Finally it registers the service with the fabric via the register_service_sync() method of the DxlClient.

#
# Register the service
#

# Create incoming request callback
class MyRequestCallback(RequestCallback):
    def on_request(self, request):
        # Extract information from request
        print("Service received request payload: " + request.payload.decode())
        # Create the response message
        res = Response(request)
        # Populate the response payload
        res.payload = "pong".encode()
        # Send the response
        client.send_response(res)

# Create service registration object
info = ServiceRegistrationInfo(client, "myService")

# Add a topic for the service to respond to
info.add_topic(SERVICE_TOPIC, MyRequestCallback())

# Register the service with the fabric (wait up to 10 seconds for registration)
client.register_service_sync(info, 10)

Invoke Service

The second section sends a Request message to the service that contains a payload of ping via the sync_request() method of the DxlClient.

The payloads of the Request and Response messages are printed.

#
# Invoke the service (send a request)
#

# Create the request message
req = Request(SERVICE_TOPIC)

# Populate the request payload
req.payload = "ping".encode()

# Send the request and wait for a response (synchronous)
res = client.sync_request(req)

# Extract information from the response (if an error did not occur)
if res.message_type != Message.MESSAGE_TYPE_ERROR:
    print("Client received response payload: " + res.payload.decode())

Output

The output should appear similar to the following:

Service received request payload: ping
Client received response payload: pong

Clone this wiki locally