Java Reference
In-Depth Information
while (true)
{
// accept() does not return until a client
// requests a connection
Socket client
-
socket = server
-
socket.accept ();
// Now that a client has arrived, create an
// instance of our Worker thread subclass to
// tend to it.
Worker worker = new Worker (client
-
socket);
worker.start ();
System.out.println ("New client connected");
}
} // main
} // class SnapAdcServer
The SNAP I/O package does not include the
PrintWriter
class so we use
PrintStream
instead. We flush the stream after each set of print meth-
ods to ensure all data is moved from the internal buffers. We note that, like
PrintWriter
, the
PrintStream
methods don't throw
IOException
and
instead the class offers the
checkError()
method, which returns true if an
IOException
occurred. (As we discussed in Chapter 14, you could modify this
code to check for errors after every print invocation or put the print statements
into utility methods that throw
IOException
as we did with the
DataWorker
class discussed in Chapter 15.)
Another difference with the
MicroServer
application in Chapter 14 is that
the
split()
method in
String
class is not available in the SNAP
java.lang
package. So we created a
split()
in the
Worker
class to located substrings,
i.e. tokens, separated by blank spaces.
import java.net.*;
import java.io.*;
import java.util.*;
import com.dalsemi.system.*;
/** Threaded process to serve the client connected to
* the socket. **/
public class
Worker
extends Thread {
Socket fClient;
String fWebPageTop =
Search WWH ::
Custom Search