Java Reference
In-Depth Information
The server should now respond with a definition. You can read that using the socket's
input stream:
InputStream in = socket . getInputStream ();
BufferedReader reader = new BufferedReader (
new InputStreamReader ( in , "UTF-8" ));
for ( String line = reader . readLine ();
! line . equals ( "." );
line = reader . readLine ()) {
System . out . println ( line );
}
When you see a period on a line by itself, you know the definition is complete. You can
then send the quit over the output stream:
writer . write ( "quit\r\n" );
writer . flush ();
Example 8-4 shows a complete dict client. It connects to dict.org , and translates any
words the user enters on the command line into Latin. It filters out all the metadata lines
that begin with response codes such as 150 or 220. However, it does specifically check
for a line that begins “552 no match” in case the server doesn't recognize the word.
Example 8-4. A network-based English-to-Latin translator
import java.io.* ;
import java.net.* ;
public class DictClient {
public static final String SERVER = "dict.org" ;
public static final int PORT = 2628 ;
public static final int TIMEOUT = 15000 ;
public static void main ( String [] args ) {
Socket socket = null ;
try {
socket = new Socket ( SERVER , PORT );
socket . setSoTimeout ( TIMEOUT );
OutputStream out = socket . getOutputStream ();
Writer writer = new OutputStreamWriter ( out , "UTF-8" );
writer = new BufferedWriter ( writer );
InputStream in = socket . getInputStream ();
BufferedReader reader = new BufferedReader (
new InputStreamReader ( in , "UTF-8" ));
for ( String word : args ) {
define ( word , writer , reader );
}
writer . write ( "quit\r\n" );
writer . flush ();
Search WWH ::




Custom Search