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
-
Access the web interface by entering the device's IP address in a browser's URL
window.
-
Configure the device to function as a TCP server by doing the following:
-
Choose Serial Ports from the Configuration menu.
-
Click the TCP tab.
-
Check 'Enable normal TCP server'.
-
Specify the Raw TCP port (the default is 2101).
-
Uncheck 'Automatically establish TCP connections'.
-
Click Save.
-
Configure the device to authenticate users by doing the following (optional):
-
Choose Security from the Configuration menu.
-
Check 'Enable password authentication'.
-
Specify a user name and password.
-
Click Save.
-
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
-
Open a command prompt.
-
Go to the messenger directory.
-
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.
-
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
-
Select File Management under the Administration menu.
-
Click Browse. Locate and select the messenger.jar file in the messenger\dist\bin\applet
directory. Click Open.
-
Click Upload.
-
Click Browse. Locate and select the messenger.htm file in the messenger\dist\bin\applet
directory. Click Open.
-
Click Upload.
-
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.
-
Open a command prompt.
-
Go to the messenger\dist\bin\applet directory.
-
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.
- 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");
- 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>";
- 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();
- 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.
- Create the socket to establish a TCP connection
socket = new Socket(host, port);
- 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);
}
}
- Transmit data
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println(msgText);
out.flush();
- 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.
|