LCM
Java Tutorial

Sending and receiving LCM messages with Java

Introduction

This tutorial will show you how to use all of the core functionality of LCM, and is intended for those who have a working knowledge of Java. For detailed information about LCM, please see the Java API reference.

The topics covered in this tutorial are:

This tutorial uses the example_t message type defined in the type definition tutorial, and assumes that you have generated the Java bindings for the example type by running

1 lcm-gen -j example_t.lcm

After running this command, you should have one file, exlcm/example_t.java. This file is the Java binding for the example message type. If you have the time, take a moment to open up the file and inspect the generated code.

You can then compile this into a .class file, and then create a .jar archive. Assuming that lcm.jar is in the current directory (see the Java notes page), you could then run (also from a command shell):

1 javac -cp lcm.jar exlcm/*.java
2 jar cf my_types.jar exlcm/*.class

You should then have a file my_types.jar, which is a Java archive containing the Java bindings for the example message. In order to use LCM types, you must include the jar file on your classpath.

Initializing LCM

You will need to make sure that lcm.jar is in your classpath, and your Java classes will need to include "import lcm.lcm.*".

To initialize LCM, with default options, simply call:

1 LCM myLCM = LCM.getSingleton();

The default options are suitable for communicating with other LCM applications on the local computer. For communication across computers, or other usages such as reading data from an LCM logfile (e.g., to post-process or analyze previously collected data), see the Java API reference.

Publishing a message

We can instantiate and then publish some sample data as follows:

1 import java.io.*;
2 import lcm.lcm.*;
3 
4 public class SendMessage
5 {
6  public static void main(String args[])
7  {
8  try {
9  LCM lcm = LCM.getSingleton();
10 
11  exlcm.example_t msg = new exlcm.example_t();
12  msg.timestamp = System.nanoTime();
13  msg.position = new double[] { 1, 2, 3 };
14  msg.orientation = new double[] { 1, 0, 0, 0 };
15  msg.ranges = new short[] {
16  0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
17  };
18  msg.num_ranges = msg.ranges.length;
19  msg.name = "example string";
20  msg.enabled = true;
21 
22  lcm.publish("EXAMPLE", msg);
23  } catch (IOException ex) {
24  System.out.println("Exception: " + ex);
25  }
26  }
27 }

After initializing LCM, this application creates an instance of the example message, fills in some message fields, and then publishes the message.

The call to lcm.publish() serializes the data into a byte stream and transmits the packet using LCM to any interested receivers. The string "EXAMPLE" is the channel name, which is a string transmitted with each packet that identifies the contents to receivers. Receivers subscribe to different channels using this identifier, allowing uninteresting data to be discarded quickly and efficiently.

Subscribing to messages

In order to receive messages, you must implement an LCMSubscriber and pass it to LCM.subscribe(). The subscriber will be provided with a LCMDataInputStream that can be read for the message contents. All LCM data types include a constructor that takes a DataInput (including instances of LCMDataInputStream) as an argument. First, let's look at the subscriber:

1 public class MySubscriber implements LCMSubscriber
2 {
3  public void messageReceived(LCM lcm, String channel, LCMDataInputStream ins)
4  {
5  System.out.println("Received message on channel " + channel);
6  example_t msg;
7  try {
8  msg = new example_t(ins);
9  } catch (IOException ex) {
10  System.out.println("Error decoding message: " + ex);
11  return;
12  }
13 
14  System.out.println(" timestamp = " + msg.timestamp);
15  // Could do something else with the message here.
16  }
17 }

Next, we can subscribe to the message with:

1 lcm.subscriber("EXAMPLE", new MySubscriber());

The LCM instance has a background thread that constantly listens for messages. When a message on channel "EXAMPLE" arrives, the LCM thread will invoke the messageReceived() method.

Putting it all together

Here's an example of a complete subscriber application:

1 import java.io.*;
2 
3 import lcm.lcm.*;
4 import exlcm.*;
5 
6 public class MySubscriber implements LCMSubscriber
7 {
8  LCM lcm;
9 
10  public MySubscriber()
11  throws IOException
12  {
13  this.lcm = new LCM();
14  this.lcm.subscribe("EXAMPLE", this);
15  }
16 
17  public void messageReceived(LCM lcm, String channel, LCMDataInputStream ins)
18  {
19  System.out.println("Received message on channel " + channel);
20 
21  try {
22  if (channel.equals("EXAMPLE")) {
23  example_t msg = new example_t(ins);
24 
25  System.out.println(" timestamp = " + msg.timestamp);
26  System.out.println(" position = [ " + msg.position[0] +
27  ", " + msg.position[1] + ", " + msg.position[2] + " ]");
28  System.out.println(" orientation = [ " + msg.orientation[0] +
29  ", " + msg.orientation[1] +
30  ", " + msg.orientation[2] +
31  ", " + msg.orientation[3] + " ]");
32 
33  System.out.print(" ranges = [ ");
34  for (int i=0; i<msg.num_ranges; i++) {
35  System.out.print("" + msg.ranges[i]);
36  if (i < msg.num_ranges-1)
37  System.out.print (", ");
38  }
39  System.out.println (" ]");
40  System.out.println(" name = '" + msg.name + "'");
41  System.out.println(" enabled = '" + msg.enabled + "'");
42  }
43 
44  } catch (IOException ex) {
45  System.out.println("Exception: " + ex);
46  }
47  }
48 
49  public static void main(String args[])
50  {
51  try {
52  MySubscriber m = new MySubscriber();
53  while(true) {
54  Thread.sleep(1000);
55  }
56  } catch (IOException ex) {
57  System.out.println("Exception: " + ex);
58  } catch (InterruptedException ex) { }
59  }
60 }

The full example is included in the LCM source distribution, in the examples/java directory.

Compiling and running

To compile and run the examples, let's assume that the lcm.jar file is in the current directory, along with SendMessage.java, MySubscriber.java, and example_t.lcm. We can run our programs by executing the commands:

# 1. Create the Java implementation of temperature_t.lcm
lcm-gen -j example_t.lcm

# 2. Compile the demo applications and the LCM type created above.
javac -cp .:lcm.jar *.java exlcm/*.java

# 3. Run MySubscriber (in one terminal)
java -cp .:lcm.jar MySubscriber 

# 4. Run SendMessage (in another terminal)
java -cp .:lcm.jar SendMessage 

Additional notes

See the Java notes page for some additional information related to LCM development with Java.