代码学习

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 arguments
if ((args.length != 1)&& (args.length != 2))
throw new IllegalArgumentException("Wrong number of args");

// Set up the streams
URL url = new URL(args[0]); // Create the URL
in = url.openStream(); // Open a stream to it
if (args.length == 2) // Get an appropriate output stream
out = new FileOutputStream(args[1]);
else out = System.out;

// Now copy bytes from the URL to the output stream
byte[] 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 <URL> [<filename>]");
}
finally { // Always close the streams, no matter what.
try { in.close(); out.close(); } catch (Exception e) {}
}
}
}


===========================================================


package com.davidflanagan.examples.net;
import jsp servlet ejb .io.*;
import jsp servlet ejb .net.*;

/**
* 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 console
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));

// Ask the user for the from, to, and subject lines
System.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 mail
URL u = new URL("mailto:" + to); // Create a mailto: URL
URLConnection c = u.openConnection(); // Create its URLConnection
c.setDoInput(false); // Specify no input from it
c.setDoOutput(true); // Specify we'll do output
System.out.println("Connecting..."); // Tell the user
System.out.flush(); // Tell them right now
c.connect(); // Connect to mail host
PrintWriter out = // Get output stream to host
new PrintWriter(new OutputStreamWriter(c.getOutputStream()));

// Write out mail headers. Don't let users fake the From address
out.print("From: /"" + from + "/" <" +
System.getProperty("user.name") + "@" +
InetAddress.getLocalHost().getHostName() + ">/n");
out.print("To: " + to + "/n");
out.print("Subject: " + subject + "/n");
out.print("/n"); // blank line to end the list of headers

// Now ask the user to enter the body of the message
System.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");
}

// Close (and flush) the stream to terminate the message
out.close();
// Tell the user it was successfully sent.
System.out.println("Message sent.");
}
catch (Exception e) { // Handle any exceptions, print error message.
System.err.println(e);
System.err.println("Usage: jsp servlet ejb SendMail [<mailhost>]");
}
}
}


=================================================================


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 arguments
if ((args.length != 1) && (args.length != 2))
throw new IllegalArgumentException("Wrong number of args");

// Get an output stream to write the URL contents to
OutputStream 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 protocol
throw 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 port
String filename = url.getFile();

// Open a network socket connection to the specified host and port
Socket socket = new Socket(host, port);

// Get input and output streams for the socket
InputStream 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 protocol
to_server.print("GET " + filename + "/n/n");
to_server.flush(); // Send it right now!

// Now read the server's response, and write it to the file
byte[] buffer = new byte[4096];
int bytes_read;
while((bytes_read = from_server.read(buffer)) != -1)
to_file.write(buffer, 0, bytes_read);

// When the server closes the connection, we close our stuff
socket.close();
to_file.close();
}
catch (Exception e) { // Report any errors that arise
System.err.println(e);
System.err.println("Usage: jsp servlet ejb HttpClient <URL> [<filename>]");
}
}
}


==========================================================

/*
* 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),
* visit
http://www.davidflanagan.com/javaexamples2 .
*/
package com.davidflanagan.examples.net;
import jsp servlet ejb .io.*;
import jsp servlet ejb .net.*;

/**
* This class uses 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))
throw new IllegalArgumentException("Wrong number of args");

// Create the Server object
Server 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 < args.length) {
String host = args[i++];
int remoteport = Integer.parseInt(args[i++]);
int localport = Integer.parseInt(args[i++]);
s.addService(new Proxy(host, remoteport), localport);
}
}
catch (Exception e) { // Print an error message if anything goes wrong
System.err.println(e);
System.err.println("Usage: jsp servlet ejb ProxyServer " +
"<host> <remoteport> <localport> ...");
System.exit(1);
}
}

/**
* 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 some sockets we'll use. They are final so they can
// be used by the anonymous classes defined below.
final InputStream 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;
}

// Create an array to hold two Threads. It is declared final so
// that it can be used by the anonymous classes below. We use an
// array instead of two variables because given the structure of
// this program two variables would not work if declared final.
final Thread[] threads = new Thread[2];

// Define and create a thread to copy bytes from client to server
Thread c2s = new Thread() {
public void run() {
// Copy bytes 'till EOF from client
byte[] buffer = new byte[2048];
int bytes_read;
try {
while((bytes_read=from_client.read(buffer))!=-1) {
to_server.write(buffer, 0, bytes_read);
to_server.flush();
}
}
catch (IOException e) {}
finally {
// When the thread is done
try {
server.close(); // close the server socket
to_client.close(); // and the client streams
from_client.close();
}
catch (IOException e) {}
}
}
};

// Define and create a thread to copy bytes from server to client.
// This thread works just like the one above.
Thread s2c = new Thread() {
public void run() {
byte[] buffer = new byte[2048];
int bytes_read;
try {
while((bytes_read=from_server.read(buffer))!=-1) {
to_client.write(buffer, 0, bytes_read);
to_client.flush();
}
}
catch (IOException e) {}
finally {
try {
server.close(); // close down
to_client.close();
from_client.close();
} catch (IOException e) {}
}
}
};

// Store the threads into the final threads[] array, so that the
// anonymous classes can refer to each other.
threads[0] = c2s; threads[1] = s2c;

// start the threads
c2s.start(); s2c.start();

// Wait for them to exit
try { c2s.join(); s2c.join(); } catch (InterruptedException e) {}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值