Digi Homepage Making Device Networking Easy.
 

Java Messenger Sample

Introduction

This sample demonstrates how to write a Java application to communicate with a device server. The following concepts are illustrated:

  • TCP Sockets communication
  • HTTP communication
  • Authentication
  • Remote Command Interface (RCI)

This sample works much like an instant messenger application. Messages typed in by the user are sent over the network to the first serial port on the device server, and any data initiated on the serial port of the device server is sent over the network and received by the Messenger application.

You can run the Messenger standalone by attaching a loopback plug to the serial port. In this configuration the messages sent by the user are echoed back to the Messenger application.

You can also run the Messenger with a terminal attached by connecting a PC to the serial port of the device server and running a terminal emulation program such as HyperTerminal. Messages sent from the Messenger application will show up in the terminal emulation program and messages typed in the terminal will show up in the Messenger application.

For the purpose of this demonstration, the messenger application first initiates communication with the device server using HTTP to access device configuration information. This is also when authentication is performed, if necessary. The application then creates a socket to establish a TCP connection to the first serial port on the device server. It uses this socket to transmit and receive data to/from the device server.

Device Server Setup

This sample was designed to operate with the first port on the device server, and requires that the port be configured to listen for and accept raw socket connections. The autoconnect feature must also be disabled.

Configure the device server

  1. Access the web interface by entering the device's IP address in a browser's URL window.
  2. Configure the device to function as a TCP server by doing the following:
    1. Choose Serial Ports from the Configuration menu.
    2. Click the TCP tab.
    3. Check 'Enable normal TCP server'.
    4. Specify the Raw TCP port (the default is 2101).
    5. Uncheck 'Automatically establish TCP connections'.
    6. Click Save.
  3. Configure the device to authenticate users by doing the following (optional):
    1. Choose Security from the Configuration menu.
    2. Check 'Enable password authentication'.
    3. Specify a user name and password.
    4. Click Save.
  4. Connect the loopback plug to port 1 if running in standalone mode, or connect a serial cable between port 1 and your PC and run a terminal emulation program.

How To Build

This sample has been written and tested with the J2SE 1.4.2 SDK and can be built using Apache Ant 1.5.3. These can be downloaded from the following locations:

To build this sample

  1. Open a command prompt.
  2. Go to the messenger directory.
  3. Execute the build.bat file, specifying the target 'all' (e.g. build all)

Two environment variables are required to build the sample: JAVA_HOME and ANT_HOME. The default values for these are C:\j2sdk1.4.2 and C:\apache-ant-1.5.3-1, respectively. If you install Java or Ant into different directories you will need to set these environment variables appropriately.

Output of the build

The build creates 2 subdirectories: build and dist. The build subdirectory contains the all the generated class files, javadoc files, jar files, etc. The dist subdirectory is intended to be used as a self-contained distribution of the application and contains the jar files and associated files to execute the application or applet.

How To Run

This sample can be run as an applet or an application. When run as an applet the messenger resides on the device and is downloaded and run from within a browser on your PC. When run as an application the messenger resides on your PC and is executed from there.

Note: Messenger must be restarted whenever the cabling is changed on the serial port (such as connecting or disconnecting the loopback plug).

To run as an applet:

You must load the jar and HTML files onto the device (this only has to be done once). When executed, the Messenger applet will connect back to the device it was loaded from.

  1. Access the administration web interface by entering the following URL in in a browser's URL window:
        http://ip-address-of-device/admin/administration.htm
  2. Select File Management under the Administration menu.
  3. Click Browse. Locate and select the messenger.jar file in the messenger\dist\bin\applet directory. Click Open.
  4. Click Upload.
  5. Click Browse. Locate and select the messenger.htm file in the messenger\dist\bin\applet directory. Click Open.
  6. Click Upload.
  7. Click messenger.htm to run the Messenger applet from the device (to access the applet directly use the URL http://ip-address-of-device/FS/WEB/messenger.htm).

To run as an application:

Execute the batch file provided. You must specify the IP address of the device you want the Messenger application to connect to.

  1. Open a command prompt.
  2. Go to the messenger\dist\bin\applet directory.
  3. Execute the messenger.bat file, specifying the IP address of the device (e.g. messenger 192.168.1.100).

Sending messages:

Once the Messenger application or applet is running you can type a message into the text box on the bottom left of the window and click Send. The message will be sent to the device. The message will also be displayed in the message area on the top left of the window, prefixed with 'send:'.

When messages are received from the device they will also be shown in the message area on the top left of the window. These messages will be prefixed with 'recv:'. If a loopback is attached to the serial port then messages will be echoed back immediately. If a PC is connected to the serial port then you must type a message followed by the enter key in the terminal emulation program.

Any messages generated internally by the Messenger application will be displayed in the message area with a different prefix.

Step-by-Step

Overview

This sample first retrieves some serial port configuration information from the device using HTTP and the RCI protocol. If authentication is required a login prompt is displayed at this time. The configuration is then validated and the raw TCP port number is used to create a socket and initiate a TCP connection to the device. This socket is used for all subsequent communication to the device.

The following classes implement this functionality. All other classes deal with the user interface.

  • MessengerConfig: retrieves configuration information using HTTP and RCI.
  • Messenger: performs all TCP socket communications.
  • Authentication: displays a login prompt when network authentication is required. This class implements the java.net.Authenticator interface.

1.  Initialize Authentication

The following initialization code is in the initialize function of the MessengerPanel class. It sets the Authentication class as the default network authenticator. If authentication is required by the HTTP server in the device then the getPasswordAuthentication function of this class will be called and a login prompt will be displayed.

Authenticator.setDefault(new Authentication(this));
                

2.  Retrieve Configuration Information

The query function of the MessageConfig class sends an RCI request to the device to query configuration information. This request is sent to the URL http://ip-address-of-device/UE/rci using HTTP.

The following steps are performed in the sendCommand function, which is called by the query function.

  1. Open an HTTP connection
    URL url = new URL("http://"+host+"/UE/rci");
    URLConnection connection = url.openConnection();
    
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestProperty("content-type","application/x-www-form-urlencoded");
    
                            
  2. Send the RCI query to the device
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.writeBytes(command.toString());
    // flush output stream
    out.flush(); 
    out.close();
    
                            
    The RCI query command that is sent is in XML format and is defined in the QUERY_CONFIG_COMMAND variable:
    private static final String QUERY_CONFIG_COMMAND =
        "<rci_request version=\"1.0\">" +
        "  <query_setting>" +
        "    <tcp_server/>" +
        "    <autoconnect/>" +
        "  </query_setting>" +
        "</rci_request>";
    
                            
  3. Receive the response
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuffer resultMsg = new StringBuffer();
    String line;
    while ((line = in.readLine()) != null) {
        resultMsg.append(line);
    }
    in.close();
    
                            
  4. Parse the response into a DOM tree
    ByteArrayInputStream bais = new ByteArrayInputStream(resultMsg.toString().getBytes());
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
    Document resultDocument = domBuilder.parse(bais);
    
                            

3.  TCP Socket Communications

After retrieving configuration information this sample establishes a TCP connection for transmitting and receiving messages. This processing all happens within the Messenger class.

The start function creates a new thread that receives data. The receive function creates a socket and then continually reads the socket's input stream. The send function creates a new thread to send data using this same socket. The stop function closes the socket.

  1. Create the socket to establish a TCP connection
    socket = new Socket(host, port);
    
                            
  2. Receive data
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    while (true) {
        String msg = in.readLine();
        if (msg != null && msg.length() > 0) {
            displayMessage(RECEIVE_PREFIX+msg);
        }
    }
    
                            
  3. Transmit data
    PrintWriter out = new PrintWriter(socket.getOutputStream());
    out.println(msgText);
    out.flush();
    
                            
  4. Close the socket
    socket.close();
    
                            

File List

build.bat - Batch file to build the sample using Ant and the build.xml file.
build.xml - Ant build file.
Authentication.java - Network authentication.
MessageDisplay.java - Interface for displaying messages.
Messenger.java - TCP socket communications.
MessengerApplet.java - Applet.
MessengerApplication.java - Application.
MessengerConfig.java - HTTP/RCI communications for configuration.
MessengerPanel.java - Primary UI for the applet and the application.
 
 
Digi International Inc. 11001 Bren Road E. Minnetonka, MN 55343
PH: (952) 912-3444 or 877-912-3444
FX: (952) 912-4952