Chapter 14. Building roll your own clients 291
Closing the socket connection
To close the socket connection, use the close() function using the socket descriptor as a
parameter.
In the sample program, we use a
transaction socket. That means that the IMS Connect host
will close the connection as soon as the transaction has completed. Therefore, if we try to
send a second transaction to IMS, we receive an input output error, because we are trying to
write to a socket that has the remote end closed. If we want to send more than one
transaction without reopening the socket, we use a
permanent socket. See Chapter 7, “IMS
Connect programming model” on page 91 to learn more about transaction and permanent
sockets.
If you have used IMS Connector for Java, you are familiar with
shared and dedicated
connections. This concept has nothing to do with non-IMS Connector for Java clients, and it is
specific to the JCA implementation.
14.5.2 Java example
The complete source code listing is in Example A-2 on page 484. In this section, we review
some code excerpts that are relevant to this chapter.
Program structure
The Java sample consists on a single class (Sample), which contains methods to prepare,
send, and receive information to and from IMS Connect, and a static main method to parse
the command line to get parameters and data to build the transaction. Even though this is not
the
correct way of doing things in Java, it will suffice to show you the IMS Connect
programming specifics so that you can build on it.
Obtain a stream socket connection to the IMS Connect server
This is straightforward in Java. Example 14-7 shows the way to do it. The Socket constructor
takes care of the host name translation and returns an opened, ready-to-use socket object
reference.
Example 14-7 Opening a socket connection in Java
/**
* Establish a socket connection with the IMS Connect host
*/
public void connect() {
try {
// open a socket for the transaction
socket = new Socket(hostName, portNumber);
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
}
Preparing and sending the message to IMS Connect
Example 14-8 shows the code we use to send a message to IMS Connect in Java. This code
is very similar to the code we reviewed in Example 14-5 on page 284. The only relevant
differences are:
We do not need to do any translation between the network and host byte orders. We use a
DataOutputStream object to prepare the IRM, and the write() method of that Class already
converts the binary integers to big endian order.