package com.davidflanagan.examples.net; import jsp servlet ejb .io *;. import jsp servlet ejb .net *;. / *** This simple program uses the URL class and its openStream () method to * download the contents of . a URL and copy them to a file or to the console ** / public class GetURL {public static void main (String [] args) {InputStream in = null; OutputStream out = null; try {// Check the argumentsif (( Args.Length! = 1) && (args.length! = 2)) Throw new iLlegaArgumentException ("Wrong Number of Args"); // set up the streamsurl URL = New URL (Args [0]); // Create THE Urlin = url.openStream (); // Open a stream to itif (args.length == 2) // get an appropriate output streamout = new fileoutputstream (args [1]); else out = system.out; // NOW Copy Bytes from the url to the output streambyte [] buffer = new byte [4096]; int Bytes_read; while ((bytes_read = in.read (buffer))! = -1) Out.write (buffer, 0, bytes_read); } // on exceptions, print error message and usage message.catch (exception e) {system.err.println (e); system.err. Println ("Usage: JSP Servlet EJB GETURL
/ *** This Program Sends E-mail Using a mailto: URL ** / public class sendmail {public static void main (string [] args) {try {// if the user specified a mailhost, tell the system about it. if (args.length> = 1) System.getProperties () put ( "mail.host", args [0]);. // A Reader stream to read from the consoleBufferedReader in = new BufferedReader (new InputStreamReader (System.in )); // ask, and SUBJECT LINESSYSTEM.OUT.PRINT ("from:"); string from = in.readline (); system.out.print ("to:"); String To = in.readLine (); system.out.print ("Subject:"); string subject = in.readLine (); // establish a network connection for sending mailurl u = new url ("mailto:" to) ; // Create a mailto: URL URLConnection c = u.openConnection (); // Create its URLConnectionc.setDoInput (false); // Specify no input from itc.setDoOutput (true); // Specify we'll do outputSystem. Out.println ("Connecting ..."); // Tell the usersystem.out.flush (); // Tell the right nowc.connect (); // connect To mail hostprintwriter out = // get output stream to hostnew printwriter (c.getoutstreamwriter); // Write out mail headers. Don't let users fake the from addressout.print ("from: /" " from " / "<" System.getProperty ("User.Name") "@" inetaddress.getlocalhost (). GetHostName () "> / n"); Out.Print ("to:" to "/ n "); Out.print (" Subject: " Subject " /N "); // blank line to end the list of headers // now ask the user to enter the user To Enter T Body of the messageSystem.out.println ("Enter the message."
"End with a '.' On a line by itself."); // read Message line by line and send it out.string line; for (;;) {line = in.readline (); if ((line = = NULL) || line.equals ("."))) Break; out.print (line "/ n");} // clous (and flush) the streste.close (); // Tell the user it at success.println ("message Sent.");} Catch (Exception E) {// Handle Any Exceptions, Print Error Message.System.err.Println (E); System.err .println ("USAGE: JSP servlet ejb sendmail");}}} ============================= ====================================================== package com.davidflanagan.examples.net; Import JSP Servlet EJB. io *;. import jsp servlet ejb .net *;. / *** This program connects to a Web server and downloads the specified URL * from it It uses the HTTP protocol directly ** / public class HttpClient {public static void.. Main (String [] args) {try {// check the argumentsif ((args.length! = 1) && (args.length! = 2)) throw new iLlegaLaMumeTexception ("Wrong Number of Args"); // Get An OU tput stream to write the URL contents toOutputStream to_file; if (args.length == 2) to_file = new FileOutputStream (args [1]); else to_file = System.out; // Now use the URL class to parse the user-specified URL INTO // ITS Various Parts. URL URL = New URL (Args [0]); String Protocol = Url.getProtocol (); if (! Protocol.equals ("http"
)) // Check That We support The Protocolthrow New IllegalargumentException ("Must Use 'http:' protocol"); string host = url.gethost (); int port = url.getport (); if (port == -1) Port = 80; // if no port, use the default http portstring filename = url.getfile (); // Open a network socket connection to the specified host and portsocket socket = new socket (host, port); // Get INPUT and output streams for the socketInputStream from_server = socket.getInputStream (); PrintWriter to_server = new PrintWriter (socket.getOutputStream ()); // Send the HTTP GET command to the Web server, specifying the file // This uses an old and very Simple version of the http protocolto_server.print ("get" filename "/ n / n"); to_server.flush (); // send it right now! // no write ket the server's response, and write it to the filebyte [] buffer = new byte [4096]; int Bytes_read; while ((Bytes_read = from_server.read)! = -1) TO_FILE.WRITE (Buffer, 0, Bytes_read); //hen the server closss the connection, We close our stuffsocket.c Lose (); to_file.close ();} catch (Exception E) {// Report Any Errors That Arisesystem.err.Println (e); System.err.Println ("USAGE: JSP Servlet EJB HTTPCLIENT
/ ** Copyright (c) 2000 David Flanagan. All rights reserved. * This code is from the book jsp servlet ejb Examples in a Nutshell, 2nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * you may study, use, and modify it for any non-commercial purpose. * you may distribute it non-commercially as long as you retain this notice. * for a commercial use license, or to purchase the book (recommended), * visithttp : //www.davidflanagan.com/javaexamples2
. * / pack JSP servlet ejb .io. *; import JSP servlet EJB .NET. *; / *** this class buys the server class to provide a multi-threaded Server * framework for a relatively simple proxy service. The main () method * starts up the server. The nested Proxy class implements the * Server.Service interface and provides the proxy service. ** / public class ProxyServer {/ ** * Create a Server object, and add Proxy service objects to it to provide * proxy service as specified by the command-line arguments. ** / public static void main (String [] args) {try {// Check number of args. Must be a multiple of 3 And> 0.IF ((args.length == 0) || (args.length% 3! = 0)) "Wrong Number of Args"); // Create The Server ObjectServer S = New Server NULL, 12); // LOG Stream, Max Connections // Loop THROUGH THE ARGUMENTS PARSING (HOST, Remoteport, Localport) // Tuples. For each, create a proxy, and add it to the server.int i = 0; while (i
}} / *** This is the class that implements the proxy service. The serve () method * will be called when the client has connected. At that point, it must * establish a connection to the server, and then transfer bytes back and * forth between client and server. For symmetry, this class implements * two very similar threads as anonymous classes. One thread copies bytes * from client to server, and the other copies them from server to client. * The thread that invoke the serve () method creates and starts these * threads, then just sits and waits for them to exit ** / public static class Proxy implements Server.Service {String host;. int port; / ** Remember the host and port we are a proxy for * / public Proxy (String host, int port) {this.host = host; this.port = port;}. / ** The server invokes this method when a client connects * / public void serve (InputStream in, OutputStream out ) {// THESE ARE. The anonymous classes defined BELOW.FINAL InputStre am from_client = in; final OutputStream to_client = out; final InputStream from_server; final OutputStream to_server; // Try to establish a connection to the specified server and port // and get sockets to talk to it Tell our client if we fail.final. Socket server; try {server = new Socket (host, port); from_server = server.getInputStream (); to_server = server.getOutputStream ();} catch (Exception e) {PrintWriter pw = new PrintWriter (new OutputStreamWriter (out)) PW.PRINT ("Proxy Server Could Not Connect To" Host ":" Port "/N" :pw.flush(); pw.close();Try {in.close ();} catch IOEXCEPTION EX) {} return;