Curso JAVA
Unidad 8: "Red"
Objetivos de la Unidad:
1.- Introducci�n
Servidor Web desarrollado en esta unidad pero
ampliado con un soporte b�sico de Servlets. Se incluye el c�digo fuente
completo. La unidad did�ctica de los servlets es la 12.
En relaci�n a tener informaci�n sobre el
ancho de banda que disponemos una primera aproximaci�n puede obtenerse con el
Speed Test Thermometer disponible on-line en http://www.dacor.net/forms/speedtest.asp. Informaci�n para saber "qu� hay detr�s" la
obtendremos de http://www.netcraft.com. Si se dispone de ADSL puede
configurarse en router para actuar de proxy inverso y poder montar un servidor
en nuestra m�quina. Una direcci�n interesante es http://rosh.adslnet.ws/WEBserver.htm.
2.- Micro navegador Web
(peque�o cliente HTTP)
// Pincha.java (HTTP 1.0)
import
java.net.*;
import java.io.*;
public class
Pincha
{
public
static void main(String args[]) throws Exception
{
Socket s = new
Socket("www.yahoo.com", 80);
InputStream in =
s.getInputStream();
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeBytes("GET /
HTTP/1.0\r\n\r\n");
int
c;
while ((c = in.read()) !=
-1)
{
System.out.print((char) c);
}
}
}
Con HTTP 1.1 es obligatorio enviar el campo Host:
// Pincha.java (HTTP 1.1)
import
java.net.*;
import java.io.*;
public
class Pincha
{
public static void main(String args[]) throws
Exception
{
Socket s = new Socket("www.bit.es",
80);
InputStream in = s.getInputStream();
DataOutputStream
dout = new DataOutputStream(s.getOutputStream());
dout.writeBytes("GET /
HTTP/1.1\r\n");
dout.writeBytes("Host:
www.bit.es\r\n");
dout.writeBytes("\r\n");
int c;
while ((c = in.read()) !=
-1) <
{
System.out.print((char)
c);
}
}
}
// Pincha.java
import java.net.*;
import java.io.*;public class Pincha
{
public static void main(String args[]) throws Exception
{
Socket s = new Socket("50.0.0.1", 80);
InputStream in = s.getInputStream();
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeBytes("GET http://www.yahoo.com HTTP/1.0\r\n\r\n");int c;
while ((c = in.read()) != -1)
{
System.out.print((char) c);
}}
}
La librer�a est�ndar ofrece clases para manejar
conexiones HTTP. Una nueva versi�n de Pincha podr�a ser la
siguiente:
//
Pincha.java
import java.net.*;
import java.io.*;
public class Pincha
{
public
static void main(String args[]) throws Exception
{
URL url = new
URL("http://www.bit.es");
URLConnection conn =
url.openConnection();
InputStream in =
conn.getInputStream();
int c;
while ((c = in.read()) !=
-1)
{
&nnbsp;
System.out.print((char) c);
}
}
}
3.- PicoWeb
server
// PicoWeb.java
// Este ejemplo puede no funcionar bien seg�n la versi�n del navegador debido a que no leemos nada de
// lo que nos env�a. Este problema se resuelve en el ejemplo siguiente MicroWeb
import java.io.*;
import java.net.*;
import java.util.*;public class PicoWeb
{
public static void main(String args[]) throws Exception
{
ServerSocket acceptSocket = new ServerSocket(80);
System.out.println("PicoWeb esperando por el port 80...\r\n");
while(true)
{
// se queda esperando hasta recibir un impacto
Socket s=acceptSocket.accept();OutputStream output= s.getOutputStream();
DataOutputStream d = new DataOutputStream (output);
d.writeBytes("HTTP/1.0 200 OK\r\n\r\n");
d.writeBytes("<html>\r\n");
d.writeBytes("<body bgcolor=\"#FFFFFF\">\r\n");
d.writeBytes("<h2>Hola</h2><br>\r\n");
d.writeBytes("</body>\r\n");
d.writeBytes("</html>\r\n");System.out.println("Impacto de " + s.getInetAddress());
s.close();
}
}
}
4.- MicroWeb
server
import
java.net.*;
import java.io.*;
import java.util.*;
public class
MicroWeb
{
static final int port = 8080;
static final int buffer_size =
2048;
public static void main(String args[]) throws
Exception
{
ServerSocket
acceptSocket = new ServerSocket(port);
Date date =new Date();
System.out.println("MicroWeb arrancado a las " + date.toLocaleString() + " ("
+ port + ")\r\n");
while (true)
{
Socket s = acceptSocket.accept();
OutputStream output =
s.getOutputStream();
DataOutputStream d = new
DataOutputStream(output);
InputStream input = s.getInputStream();
String request;
if ((request = getRawRequest(input)) != null)
{
d.writeBytes("HTTP/1.0 200 OK\r\n\r\n");
d.writeBytes("<html>\r\n");
d.writeBytes("<body bgcolor=\"#FFFFFF\">\r\n");
d.writeBytes("<h2>Hola</h2><br>\r\n");
d.writeBytes("Esto es un ejemplo de <a href=\"http://www.bit.es\">
link </a> a Bit");
d.writeBytes("</body>\r\n");
d.writeBytes("</html>\r\n");
System.out.println("Impacto de " + s.getInetAddress() + "\r\n");
System.out.println(request);
}
input.close();
output.close();
s.close();
}
}
static
String getRawRequest(InputStream in) throws IOException
{
byte buf[] = new byte[buffer_size];
int pos=0;
int c;
while ((c = in.read()) !=
-1)
{
switch
(c)
{
case '\r':
break;
case '\n':
if (buf[pos-1]
== c)
{
return new String(buf, 0, pos); // new String(buf,0,0,pos); para JDK
1.0
}
default:
buf[pos++] =
(byte) c;
}
}
return
null;
}
}
//
MicroWeb.java
import
java.net.*;
import java.io.*;
import java.util.*;
public class
MicroWeb
{
static final int port = 8080;
static final int buffer_size =
2048;
public static void main(String args[]) throws
Exception
{
ServerSocket
acceptSocket = new ServerSocket(port);
Date date =new Date();
System.out.println("MicroWeb arrancado a las " + date.toLocaleString() + " ("
+ port + ")\r\n");
while (true)
{
Socket s = acceptSocket.accept();
OutputStream output =
s.getOutputStream();
DataOutputStream d = new
DataOutputStream(output);
InputStream input = s.getInputStream();
String request;
if ((request = getRawRequest(input)) != null)
{
// Acabar de leer si es POST
if (request.toUpperCase().indexOf("POST") >= 0)
{
int p0 = request.toLowerCase().indexOf("content-length:") + "Content-length:".length();
int p1 = request.indexOf("\n", p0+1);
String sContentLength = request.substring(p0, p1).trim();
int contentLength = Integer.parseInt(sContentLength);
StringBuffer sbPostRequest = new StringBuffer();
for (int i = 0; i < contentLength; i++)
{
sbPostRequest.append((char) input.read());
}
request += sbPostRequest.toString();
}
d.writeBytes("HTTP/1.0 200 OK\r\n\r\n");
d.writeBytes("<html>\r\n");
d.writeBytes("<body bgcolor=\"#FFFFFF\">\r\n");
d.writeBytes("<h2>Hola</h2><br>\r\n");
d.writeBytes("Esto es un ejemplo de <a href=\"http://www.bit.es\">
link </a> a Bit");
d.writeBytes("</body>\r\n");
d.writeBytes("</html>\r\n");
System.out.println("Impacto de " + s.getInetAddress() + "\r\n");
System.out.println(request);
}
input.close();
output.close();
s.close();
}
}
static
String getRawRequest(InputStream in) throws IOException
{
byte buf[] = new byte[buffer_size];
int pos=0;
int c;
while ((c = in.read()) !=
-1)
{
switch
(c)
{
case '\r':
break;
case '\n':
if (buf[pos-1]
== c)
{
return new String(buf, 0, pos); // new String(buf,0,0,pos); para
JDK 1.0
}
default:
buf[pos++] =
(byte) c;
}
}
return
null;
}
}
import
java.net.*;
import java.io.*;
import java.util.*;
public class
MicroWeb
{
static final int port = 8080;
static final int buffer_size =
2048;
public static void main(String args[]) throws Exception
{
ServerSocket
acceptSocket = new ServerSocket(port);
Date date =new Date();
System.out.println("MicroWeb arrancado a las " + date.toLocaleString() + " ("
+ port + ")\r\n");
while (true)
{
Socket s =
acceptSocket.accept();
handleGet(s);
}
}
public
static void handleGet(Socket s) throws Exception
{
OutputStream output =
s.getOutputStream();
DataOutputStream d
= new DataOutputStream(output);
InputStream input = s.getInputStream();
String request;
if ((request = getRawRequest(input)) !=
null)
{
d.writeBytes("HTTP/1.0 200 OK\r\n\r\n");
d.writeBytes("<html>\r\n");
d.writeBytes("<body
bgcolor=\"#FFFFFF\">\r\n");
d.writeBytes("<h2>Hola</h2><br>\r\n");
d.writeBytes("Esto es un ejemplo de <a href=\"http://www.bit.es\">
link </a> a Bit");
d.writeBytes("</body>\r\n");
d.writeBytes("</html>\r\n");
System.out.println("Impacto de " + s.getInetAddress() + "\r\n");
System.out.println(request);
}
input.close();
output.close();
s.close();
}
static String getRawRequest(InputStream in) throws
IOException
{
byte buf[] = new byte[buffer_size];
int pos=0;
int c;
while ((c = in.read()) !=
-1)
{
switch
(c)
{
case '\r':
break;
case '\n':
if (buf[pos-1]
== c)
{
return new String(buf, 0, pos); // new String(buf,0,0,pos); para
JDK 1.0
}
default:
buf[pos++] =
(byte) c;
}
}
return
null;
}
}
Podemos visualizar c�mo
pueden llegar par�metros desde un navegador hasta un servidor. Para ello
utilizaremos la siguiente p�gina cuyo fichero denominaremos form.html y estando
arrancado MicroWeb rellenaremos los campos y pulsaremos "Enviar":
<html>
<body
bgcolor="#FFFFFF">
<h3>Formulario de prueba</h3>
<form
action="http://localhost:8080">
Nombre: <input type="TEXT"
name="NOM"><br>
Teléfono: <input
type="TEXT" name="TEL"><br>
<input type="SUBMIT"
value="Enviar">
</form>
<h3>Ejemplo de env�o
deparámetrosmedianteunlink</h3><BR><ahref="http://localhost:8080?NOM=abc&TEL=123">Link que envía
parámetros</h3>
</body>
</html>
5.- MiniWeb server (Peque�o servidor HTTP)
import
java.net.*;
import java.io.*;
import java.util.*;
public class
WWWUtil
{
final static String version = "1.0";
final static String
mime_text_plain = "text/plain";
final static String mime_text_html =
"text/html";
final static String
mime_image_gif = "image/gif";
final static String mime_image_jpg =
"image/jpeg";
final static String
mime_app_os = "application/octet-stream";
final static String CRLF = "\r\n";
public static byte toBytes(String s)[]
{
byte b[] = new
byte[s.length()];
s.getBytes(0,b.length,b,0);
return b;
}
public static byte byteArrayConcat(byte a[], byte b[])[]
{
byte ret[] =
new byte[a.length + b.length];
System.arraycopy(a,0,ret,0,a.length);
System.arraycopy(b,0,ret,a.length,b.length);
return ret;
}
public static byte mimeHeader(String ct, int size)[]
{
return mimeHeader(200, "OK",
ct, size);
}
public static byte mimeHeader(int code, String msg,
String ct, int size)[]
{
Date d = new Date();
return toBytes("HTTP/1.0 " +
code + " " + msg + CRLF +
"Date: " +
d.toGMTString() + CRLF +
"Server: Java/" +
version + CRLF +
"Content-type: " + ct + CRLF +
(size
> 0 ?
"Content-length: " + size + CRLF :
"") + CRLF);
}
public static byte error(int code,
String msg, String fname)[]
{
String ret =
"<body>" + CRLF + "<h1>" + code + " " +
msg +"</h1>" + CRLF;
if
(fname != null)
ret += "Error when fetching URL: " + fname + CRLF;
ret +=
"</body>" + CRLF;
byte
tmp[] = mimeHeader(code, msg, mime_text_html, 0);
return
byteArrayConcat(tmp,toBytes(ret));
}
public static String
mimeTypeString(String filename)
{
String
ct;
if
(filename.endsWith(".html") || filename.endsWith(".htm"))
ct = mime_text_html;
else if
(filename.endsWith(".class"))
ct = mime_app_os;
else if
(filename.endsWith(".gif"))
ct = mime_image_gif;
else if
(filename.endsWith(".jpg"))
ct = mime_image_jpg;
else
ct = mime_text_plain;
return
ct;
}
}
// HTTPlog.java
public class HTTPlog
{
public static void error(String
entry)
{
System.out.println("Error: " + entry);
}
public static void request(String
request)
{
System.out.println(request);
}
}
// thttp.java
import java.net.*;
import
java.io.*;
import java.util.*;
public class thttp
{
public static final int
port=80;
final static String docRoot =
"./html";
final static String indexfile =
"index.html";
final static int buffer_size =
2048;
public static final int
RT_GET=1;
public static final int
RT_UNSUP=2;
public static final int
RT_END=4;
private static void handleUnsup(String
request,
OutputStream out)
{
HTTPlog.error("Unsupported Request: " + request);
}
private static void handleGet(String
request,
OutputStream
out)
{
int fsp =
request.indexOf(' ');
int nsp
= request.indexOf(' ',fsp+1);
String
filename = request.substring(fsp+1,nsp);
filename =
docRoot + filename +
(filename.endsWith("/") ?
indexfile : "");
try
{
File f = new File(filename);
if (! f.exists())
{
out.write(WWWUtil.error(404,"Not Found", filename));
return;
}
if (! f.canRead())
{
out.write(WWWUtil.error(405,"Permission Denied",filename));
return;
}
InputStream input = new FileInputStream(f);
String mime_header = WWWUtil.mimeTypeString(filename);
int n =
input.available();
out.write(WWWUtil.mimeHeader(mime_header, n));
byte buf[] = new byte[buffer_size];
while ((n = input.read(buf)) >= 0)
{
out.write(buf,0,n);
}
input.close();
}
catch
(IOException e)
{
HTTPlog.error("Exception: " + e);
}
}
private static String
getRawRequest(InputStream in)
{
try
{
byte buf[] = new byte[buffer_size];
boolean gotCR=false;
int pos=0;
int c;
while ((c = in.read()) != -1)
{
switch (c)
{
case '\r':
break;
case '\n':
if (gotCR)
return new String(buf, 0, pos); // new String(buf,0,0,pos); para
JDK 1.0
gotCR =
true;
// FALLSTHROUGH (put the 1st \n in the string)
default:
if (c != '\n') gotCR = false;
buf[pos++] = (byte) c;
}
}
}
catch
(IOException e)
{
HTTPlog.error("Receive Error");
}
return
null;
}
private static int
HTTPRequestType(String request)
{
return
request.regionMatches(true,0,"get ",0,4) ? RT_GET : RT_UNSUP;
}
public static void main(String args[])
throws Exception
{
ServerSocket
acceptSocket = new ServerSocket(port);
Date date =new
Date();
System.out.println("MiniWeb arrancado a las " +
date.toLocaleString() + " (" + port + ")\r\n");
while
(true)
{
String request;
Socket s = acceptSocket.accept();
OutputStream output = s.getOutputStream();
InputStream input = s.getInputStream();
if ((request = getRawRequest(input)) != null)
{
switch (HTTPRequestType(request))
{
case RT_GET:
handleGet(request,output);
break;
case RT_UNSUP:
default:
handleUnsup(request,output);
break;
}
HTTPlog.request(request);
}
input.close();
output.close();
s.close();
}
}
}
6.- Peque�o cliente de correo. Env�o de mensajes por SMTP
Para la especificaci�n del protocolo ver la Unidad13
import java.io.*; import java.net.*;public class EnviarMail { private String servidorCorreoSaliente = "nt";public EnviarMail () throws UnknownHostException { System.out.println("Servidor de correo = " + servidorCorreoSaliente); System.out.println("Nodo local = " + InetAddress.getLocalHost()); }public void send (String from, String to, String subject, String texto) throws IOException { checkEmailAddress(from); checkEmailAddress(to);Socket sock = new Socket(servidorCorreoSaliente, 25);DataInputStream in = new DataInputStream(sock.getInputStream()); // los convierte en utilizables DataOutputStream out = new DataOutputStream(sock.getOutputStream());String initialID = in.readLine(); System.out.println(initialID);out.writeBytes("HELO " + InetAddress.getLocalHost() + "\r\n"); System.out.println("HELO " + InetAddress.getLocalHost());String welcome = in.readLine(); System.out.println(welcome);out.writeBytes("MAIL FROM:<" + from + ">" + "\r\n"); System.out.println("MAIL FROM:<" + from + ">");String senderOK = in.readLine(); System.out.println(senderOK);out.writeBytes("RCPT TO:<" + to + ">" + "\r\n"); System.out.println("RCPT TO:<" + to + ">");String recipientOK = in.readLine(); System.out.println(recipientOK);out.writeBytes("DATA" + "\r\n"); System.out.println("DATA"); String dataOK = in.readLine(); System.out.println(dataOK);out.writeBytes("From: " + from + "\r\n"); System.out.println("From: " + from); out.writeBytes("To: " + to + "\r\n"); System.out.println("To: " + to); out.writeBytes("Subject: " + subject + "\r\n\r\n"); System.out.println("Subject: " + subject + "\n");out.writeBytes(texto + "\r\n"); System.out.println(texto);out.writeBytes("." + "\r\n"); System.out.println(".");String acceptedOK = in.readLine(); System.out.println(acceptedOK);out.writeBytes("QUIT" + "\r\n"); System.out.println("QUIT"); String quitOK = in.readLine(); System.out.println(quitOK); }public void checkEmailAddress(String email) { if (email == null || email.indexOf('@') < 0) { System.out.println("Direccion incorrecta de correo '" + email + "'"); System.exit(0); } }public static void main(String[] args) throws IOException, UnknownHostException { if (args.length != 4) { System.out.println("Uso: EnviarMail origen destino subject texto"); System.exit(0); }EnviarMail mail = new EnviarMail (); mail.send(args[0], args[1], args[2], args[3]); // from, to, subject, texto } }
Actualmente se dispone de las extensiones est�ndar JavaMail para el env�o y recepci�n de mensajes. Para trabajar con JavaMail hacen falta los paquetes de JavaMail y Java Activation (mail.jar y activation.jar). Se adjunta Emailer.java, que puede ser utilizada para enviar mensajes con ficheros adjuntos.
7.- Peque�o cliente
FTP
import sun.net.ftp.*;
import sun.net.*;
import java.net.*;
import java.io.*;public class TryFtp
{
static FtpClient ftp;
public static void main(String args[]) Exception
{
StringBuffer buf = new StringBuffer();
int ch;
ftp = new FtpClient(args[0]);
ftp.login("ftp","[email protected]");
ftp.ascii();
TelnetInputStream t = ftp.list();while((ch = t.read()) >= 0)
buf.append((char)ch);t.close();
System.out.println(buf.toString());
System.out.println("\nFichero a bajar:\n");
buf.setLength(0);while((ch = System.in.read()) != '\n')
buf.append((char)ch);t = ftp.get(buf.toString());
buf.setLength(0);while((ch = t.read()) >= 0)
buf.append((char)ch);t.close();
System.out.println(buf.toString());
}
}
8.- Peque�o servidor
FTP
/*
This program was written by S.Tanaka, E-mail: [email protected]
*/import java.io.*;
import java.net.*;
public class MyFtpd extends Thread
{
public static void main(String[] args)
{
if(args.length != 0)
{
// System.out.println(args[0]);
r = args[0];
}
else
{
r = "c:";
}int i = 1;
try
{
ServerSocket s = new ServerSocket(21);for(;;)
{
Socket incoming = s.accept();
new MyFtpd(incoming, i).start();
i++;
}
}
catch(Exception e){}}
public MyFtpd(Socket income, int c)
{
incoming = income; counter = c;
}
public void run()
{
int lng, lng1, lng2, i, ip1, ip2, ip = 1 ,h1;
String a1, a2 ,di,str1,user="",host,dir;
System.out.println(r);
dir = r;
InetAddress inet;
InetAddress localip;try
{
inet = incoming.getInetAddress();
localip = inet.getLocalHost();
host = inet.toString();
h1 = host.indexOf("/");
host = host.substring(h1 + 1);// System.out.println(host);
BufferedReader in =
new BufferedReader(new InputStreamReader(incoming.getInputStream()));PrintWriter out
= new PrintWriter(incoming.getOutputStream(),true);out.println("220 MyFtp server[JAVA FTP server written by S.Tanaka]ready.\r");
boolean done = false;
while(!done)
{
a1 = "";
a2 = "";String str = in.readLine();
if(str.startsWith("RETR"))
{
out.println("150 Binary data connection");
str = str.substring(4);
str = str.trim();
System.out.println(str);
System.out.println(dir);
RandomAccessFile outFile = new
RandomAccessFile(dir+"/"+str,"r");Socket t = new Socket(host,ip);
OutputStream out2 = t.getOutputStream();
byte bb[] = new byte[1024];
int amount;try
{
while((amount = outFile.read(bb)) != -1)
{
out2.write(bb, 0, amount);
}out2.close();
out.println("226 transfer complete");
outFile.close();
t.close();
}
catch(IOException e){}
}if(str.startsWith("STOR"))
{
out.println("150 Binary data connection");
str = str.substring(4);
str = str.trim();
System.out.println(str);
System.out.println(dir);
RandomAccessFile inFile = new
RandomAccessFile(dir+"/"+str,"rw");
Socket t = new Socket(host,ip);
InputStream in2 = t.getInputStream();byte bb[] = new byte[1024];
int amount;
try
{
while((amount = in2.read(bb)) != -1)
{
inFile.write(bb, 0, amount);
}in2.close();
out.println("226 transfer complete");
inFile.close();
t.close();
}
catch(IOException e){}
}if(str.startsWith("TYPE"))
{
out.println("200 type set");
}if(str.startsWith("DELE"))
{
str = str.substring(4);
str = str.trim();
File f = new File(dir,str);
boolean del = f.delete();
out.println("250 delete command successful");
}if(str.startsWith("CDUP"))
{
int n = dir.lastIndexOf("/");
dir = dir.substring(0,n);
out.println("250 CWD command succesful");
}if(str.startsWith("CWD"))
{
str1 = str.substring(3);
dir = dir+"/"+str1.trim();
out.println("250 CWD command succesful");
}if(str.startsWith("QUIT"))
{
out.println("GOOD BYE");
done = true;
}if(str.startsWith("USER"))
{
user = str.substring(4);
user = user.trim();
out.println("331 Password");
}if(str.startsWith("PASS"))
out.println("230 User "+user+" logged in.");if(str.startsWith("PWD"))
{
out.println("257 \""+dir+"\" is current directory");
}if(str.startsWith("SYS"))
out.println("500 SYS not understood");if(str.startsWith("PORT"))
{
out.println("200 PORT command successful");
lng = str.length() - 1;
lng2 = str.lastIndexOf(",");
lng1 = str.lastIndexOf(",",lng2-1);for(i=lng1+1;i<lng2;i++)
{
a1 = a1 + str.charAt(i);}for(i=lng2+1;i<=lng;i++)
{
a2 = a2 + str.charAt(i);
}ip1 = Integer.parseInt(a1);
ip2 =Integer.parseInt(a2);
ip = ip1 * 16 *16 + ip2;
}if(str.startsWith("LIST"))
{try
{
out.println("150 ASCII data");Socket t = new Socket(host,ip);
PrintWriter out2
= new PrintWriter(t.getOutputStream(),true);File f = new File(dir);
String[] a = new String[10];
String d,e;
int i1,j1;
a = f.list();
j1 = a.length;
d = f.getName();for(i1=0;i1<j1;i1++)
{
if( a[i1].indexOf(".") == -1) // DIR
{
di = "d ";
}
else
{
di = "- ";
}out2.println(di+a[i1]);
}t.close();
out.println("226 transfer complete");
}
catch(IOException e){}}
}incoming.close();
}
catch (Exception e)
{ // System.out.println(e);
}
}private Socket incoming;
private int counter;
private static String r;
}
Una versi�n Open Source basada en este servidor FTP pero
mucho m�s completa puede obtenerse en http://www.theorem.com/java/Free.htm#FTPServer
Comentario final: El JDK incluye en los paquetes de sun
clases como FtpClient, SmtpClient, HttpClient, NntpClient, TelnetInputStream
entre otras.
8.- RMI
La idea es poder referenciar un objeto remoto (una
instancia de una clase) como si estuviera en local y poder utilizar sus m�todos
con toda transparencia. El concepto est� basado en el design pattern denominado
proxy, simplifica enormemente todo lo relativo a servicios remotos siendo muy
id�neo para la comunicaci�n applets/servlets. Puede considerarse una
caracter�stica de gran potencia.
/**********************************
* ObjRemotoInterface.java
**********************************/
import java.rmi.*;
public interface ObjRemotoInterface extends Remote
{
String getHola() throws RemoteException;
}
/**********************************
* ObjRemoto.java
**********************************/
import java.rmi.*;
import java.rmi.server.*;
public class ObjRemoto extends UnicastRemoteObject implements ObjRemotoInterface
{
public ObjRemoto() throws RemoteException {}
public String getHola() throws RemoteException
{
System.out.println("Enviando Hola");
return "Hola";
}
}
/**********************************
* AplicacionLocal.java
**********************************/
//Nota relativa al nombre de la clase y del interface para los objetos remotos:
//
// Los nombres escogidos ObjRemoto y ObjRemotoInterface han sido escogidos para facilitar
// la comprensi�n del ejemplo inicial.
// La nomenclatura definitiva para un caso real pasar�a a ser respectivamente a
// ObjRemotoImpl y ObjRemoto
import java.rmi.*;
public class AplicacionLocal
{
public static void main(String[] args) throws Exception
{
System.setSecurityManager(new RMISecurityManager());
ObjRemotoInterface obj =
(ObjRemotoInterface) Naming.lookup("rmi://192.0.0.1:6789/prueba.ObjRemoto");
String s = obj.getHola();
System.out.println(s);
}
}/**********************************
* AplicacionRemota.java
**********************************/
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
public class AplicacionRemota
{
public static void main(String[] args) throws Exception
{
System.setSecurityManager(new RMISecurityManager());
LocateRegistry.createRegistry(6789);
ObjRemoto obj = new ObjRemoto();
Naming.rebind("//:6789/prueba.ObjRemoto", obj);
}
}
Para ejecutar en Java 2 hay que indicar en el comando de ejecuci�n el fichero de pol�ticas de seguridad a aplicar:
java -Djava.security.policy=c:\cursojava\java.policy Aplicacion<local y/o remota>
donde el java.policy m�s permisivo es:
grant
{
permission
java.security.AllPermission;
};
9.- Comunicaciones sobre Sockets encriptados
En relaci�n a SSL (Secure Sockets Layer) la p�gina de referencia es http://home.netscape.com/security/techbriefs/ssl.html. En cuanto a SSL y Java se puede encontrar informaci�n muy interesante en el DSTC australiano en http://security.dstc.edu.au/projects/java/. Y en general en cuanto a criptograf�a una buena p�gina de referencia es http://www.cs.auckland.ac.nz/~pgut001/links.html
Unidad anterior - Unidad siguiente
Copyright DENVIR STUDIOS �
Lima - Per�, 2002