FileDocCategorySizeDatePackage
KeepSocketOpen.javaAPI DocApache Xerces 3.0.116958Fri Sep 14 20:33:58 BST 2007socket

KeepSocketOpen

public class KeepSocketOpen extends Object
This sample provides a solution to the problem of 1) sending multiple XML documents over a single socket connection or 2) sending other types of data after the XML document without closing the socket connection.

The first situation is a problem because the XML specification does not allow a document to contain multiple root elements. Therefore a document stream must end (or at least appear to end) for the XML parser to accept it as the end of the document.

The second situation is a problem because the XML parser buffers the input stream in specified block sizes for performance reasons. This could cause the parser to accidentally read additional bytes of data beyond the end of the document. This actually relates to the first problem if the documents are encoding in two different international encodings.

The solution that this sample introduces wraps both the input and output stream on both ends of the socket. The stream wrappers introduce a protocol that allows arbitrary length data to be sent as separate, localized input streams. While the socket stream remains open, a separate input stream is created to "wrap" an incoming document and make it appear as if it were a standalone input stream.

To use this sample, enter any number of filenames of XML documents as parameters to the program. For example:

java socket.KeepSocketOpen doc1.xml doc2.xml doc3.xml

This program will create a server and client thread that communicate on a specified port number on the "localhost" address. When the client connects to the server, the server sends each XML document specified on the command line to the client in sequence, wrapping each document in a WrappedOutputStream. The client uses a WrappedInputStream to read the data and pass it to the parser.

Note: Do not send any XML documents with associated grammars to the client. In other words, don't send any documents that contain a DOCTYPE line that references an external DTD because the client will not be able to resolve the location of the DTD and an error will be issued by the client.

see
socket.io.WrappedInputStream
see
socket.io.WrappedOutputStream
author
Andy Clark, IBM
version
$Id: KeepSocketOpen.java 447688 2006-09-19 02:39:49Z mrglavas $

Fields Summary
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] argv)
Main program entry.


        // constants
        final int port = 6789;

        // check args
        if (argv.length == 0) {
            System.out.println("usage: java socket.KeepSocketOpen file(s)");
            System.exit(1);
        }

        // create server and client
        Server server = new Server(port, argv);
        Client client = new Client("localhost", port);

        // start it running
        new Thread(server).start();
        new Thread(client).start();