public void CrearServidor()
{
//Socket conexion;
ServerSocket sck;
BufferedReader datos;
InputStream Entradadatos;
String texto="";
int cliente=0;
int leido=0;
try
{
//Creamos un servidor
ServerSocket conexion=new ServerSocket(80,2,InetAddress.getByName("127.0.0.1"));
DataInputStream entrada=null;
DataOutputStream salida=null;
String cad="",body="",respuesta="";
byte bytedata[]=new byte[256];
while (true)
{
++cliente;
Socket conex=conexion.accept();
entrada=new DataInputStream(conex.getInputStream());
System.out.println("Cliente num "+Integer.toString(cliente));
InetAddress direc=conex.getInetAddress();
System.out.println ("Dirección de llamada"+direc.getHostAddress());
cad="";
leido=entrada.read(bytedata);
if (leido>0)
cad=new String(bytedata,0,(leido-1));
//Sacamos lo que hemos recibido desde el cliente
System.out.println("Recibido desde cliente");
System.out.println(cad);
salida=new DataOutputStream(conex.getOutputStream());
body+="<html>n";
body+="<body>n";
body+="<h1>Hola que tal!</h1>n";
body+="<image src='barra.gif'>n";
body+="</body>n";
body+="</html>n";
if (cad.indexOf("barra.gif")>=0)
{
respuesta="HTTP/1.0 200 OKn";
respuesta+="Date: Mon, 5 Nov 2001 23:59:59GMTn";
respuesta+="Content-Type: image/gifn";
respuesta+="Content-Length: 112nn";
//Hay que añadir la imagen
//Escribimos la respuesta al cliente
salida.write(respuesta.getBytes());
salida.flush();
try
{
FileInputStream imagen=new FileInputStream("barra.gif");
while((leido=imagen.read(bytedata,0,256))!=-1)
salida.write(bytedata,0,leido);
salida.flush();
}
catch (IOException e)
{
}
}
else if (cad.indexOf("hola.html")>=0)
{
respuesta="HTTP/1.0 200 OKn";
respuesta+="Date: Mon, 5 Nov 2001 23:59:59 GMTn";
respuesta+="Content-Type: text/htmln";
respuesta+="Content- Length:"+Integer.toString(body.length())+"nn";
respuesta+=body;
//Escribimos la respuesta al cliente
salida.writeBytes(respuesta);
salida.flush();
}
else
{
respuesta="HTTP/1.0 404 Error no encontradon";
respuesta+="Date: Mon, 5 Nov 2001 23:59:59 GMTn";
respuesta+="Content-Type: text/htmln";
respuesta+="Content- Length:"+Integer.toString( body.length())+"nn";
respuesta+="No se ha encontrado el documento";
//Escribimos la respuesta al cliente
salida.writeBytes(respuesta);
salida.flush();
}
//Cerramos el Socket
conex.close();
}
}
catch (IOException e)
{
System.out.println(e.toString());
System.out.println("Error al conectar");
}
}
public static void main(String[] args)
{
Comunicacion Comuc =new Comunicacion();
Comuc.CrearServidor();
//Comuc.CrearCliente();
//Comuc.pruebaURL();
}
}
Usuarios que han visto este tema también han visto...
- El paquete java.net
- Clonación de objetos en Java
- Los interfaces y la Herencia Múltiple en Java
- Introducción al J2ME
- Mensajes multi-idioma en Java
Información legal | Política de Privacidad | Contacte con nosotros
Otro proyecto de Factoría de Internet. Copyright© 2003-2011 Factoría de Internet S.L.. Todos los derechos reservados.