The NetReader and NetWriter classes
The primary message-reading and message-writing classes are the NetReader and NetWriter.
- The NetReader can be dynamically located on a network by a NetWriter based on the reader's uniquely assigned service name. Alternately, a writer can explicitly identify the remote reader's host name and port address.
- Information (messages)
can be passed between a writer and reader in several formats. These
formats include byte arrays (for binary data), Strings (for simple text information),
data records (for record-oriented data), or topical messages (that can contain
binary, String or data record information).
See the java source code located
in /osmq/test for samples of reader and writer applications. Below
is an example of a simple reader / writer pair that pass information in string
format:
NetReader
Summary
A subscriber instantiates a NetReader object and sets the NetReader's service
name and listening port. The service name is used by a remote publisher
to dynamically locate and connect to the NetReader. One or more connections
can be accepted and handled simultaneously by the NetReader. Once the
NetReader is opened, the application calls its getNextString() function to
retrieve messages. Messages are retrieved in the order in which they
were sent by the remote publisher(s).
Sample Code
import osmq.net.NetReader;
public static void main(String[] args)
{
NetReader sub;
try{
sub = new NetReader ();
// Identify the unique service name
sub.setServiceName("SAFESTORE");
// Define the listening port
sub.setPort(3843);
// If queue reaches 1000 records,
// overflow remainder to disk
sub.setOverflowSize(1000);
// Open the connection for message reception
sub.open();
// Start fetching messages as strings and printing them to the console
for(;;)
{
System.out.println("Next value = " +
sub.getNextString());
}
}
catch(Exception e)
{
System.out.println("Broker Exception");
try{System.in.read(new byte[10]);}
catch(Exception ignore){}
}
finally
{
sub.close();
}
}
NetWriter
Sample Code
import osmq.net.NetWriter;
public static void main(String[] args)
{
NetWriter pub;
try{
// instantiate the publisher
pub = new NetWriter ();
// identify the remote service
pub.setRemoteServiceName("SAFESTORE");
// connect to the service
pub.connect();
// write messages to the service
int i;
for(i = 0; i < 1000000; ++i)
pub.write("HELLO");
// close the connection
pub.disconnect();
}
catch(Exception e){}
}