// Definir el número de puerto.
// Establecer el socket de escucha.
System.err.println("servidor escuchando puerto: " + port);
// Escucha Solicitudes de servicio HTTP Proceso en un bucle infinito.
// Escucha una petición de conexión TCP.
System.err.println("Conexión establecida con :"+clientSocket.
getInetAddress().getHostName());
// Crear un objeto de procesar el mensaje de solicitud HTTP.
HttpRequest request = new HttpRequest(clientSocket);
// crea un nuevo thread que procesa la solicitud.
Thread thread = new Thread(request);
// Start the thread.
thread.start();
}
}
}
final class HttpRequest implements Runnable{
final static String CRLF = "\r\n";
Socket socket;
// Constructor
public HttpRequest(Socket socket) throws Exception
{
this.socket = socket;
}
// implementa el metodo run() de la interface Runnable.
public void run(){
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception{
// Obtener una referencia a los flujos de entrada y de salida del socket.
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
// Establecer filtros de flujo de entrada.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Obtener la línea de petición del mensaje de solicitud HTTP.
String requestLine = br.readLine();
// Mostrar la línea de petición.
System.out.println ();
System.out.println (requestLine);
// Obtener y mostrar las líneas de cabecera.
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
// Extraer el nombre del archivo en la línea de petición.
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken(); // Saltar sobre el método, que debe ser "GET"
String fileName = tokens.nextToken();
// Anteponer un "." por lo que la solicitud de archivo está en el directorio actual.
fileName = "." + fileName;
// Abra el archivo solicitado
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
// Construir el mensaje de respuesta.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "HTTP/1.1 200 OK";
contentTypeLine = "Content-type: " + contentType(fileName) + CRLF;
} else {
statusLine = "HTTP/1.1 200 OK";
contentTypeLine = "Content-type: text/html";
entityBody = "<HTML>" + "<HEAD><TITLE>Not
Found</TITLE></HEAD>" + "<BODY>Not
Found</BODY></HTML>";
}
// Enviar la línea de estado.
os.writeBytes(statusLine);
// Enviar la línea de tipo de contenido.
os.writeBytes(contentType(fileName));
// Enviar una línea en blanco para indicar el final de las líneas de cabecera.
os.writeBytes(CRLF);
// Enviar el cuerpo de la entidad.
if (fileExists) {
System.err.println("ARCHIVO ENCONTRADO");
sendBytes(fis, os);
fis.close();
} else {
System.err.println("ARCHIVO NO ENCONTRADO");
os.writeBytes(fileName);
}
// Cerrar los flujos y socket.
os.close ();
br.close ();
socket.close ();
}
private static String contentType(String fileName)
{
String TipoArchivo = "";
if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
//return "text/html";
TipoArchivo = "text/html";
}
if(fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".jpe")) {
//return "image/jpeg";
TipoArchivo = "image/jpeg";
}
if(fileName.endsWith(".db") || fileName.endsWith(".sqlite")) {
//return "image/jpeg";
TipoArchivo = "application/x-sqlite3";
}
return TipoArchivo;
}
private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception
{
// Construye un buffer 1K bytes para contener en su camino hacia el socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copia archivo en la corriente de salida del socket.
while((bytes = fis.read(buffer)) != -1 ) {
os.write(buffer, 0, bytes);
}
}
}
y
a su bes desde visual fox pro realizo una peticion al dispositivo movil
para traer un archivo determinado , estas son las lineas de vfp:Local loRequest, lcUrl, lcFilename
lcUrl = "
http://192.168.0.103:1234/sdcard/mi_imagen.jpg"
lcFilename = "C:\mi_imagen.jpg"
loRequest = Createobject('MsXml2.XmlHttp')
loRequest.Open("GET",lcUrl,.F.)
loRequest.Send()
StrToFile(loRequest.ResponseBody,lcFilename)
La
verdad que anda perfecto el funcionamiento, logro traer un archivo pero
por algun motivo no puedo visualizarlo, me dice que el archivo es
demaciado grande o esta dañado. Alguien tiene idea por que puede darse
esto? Esto me devuelve el logcat en este caso en puntual estoy tratando de enviar un archivo .db, pero para cualquier tipo de archivos me devuelve lo mismo05-08 20:09:33.388: W/System.err(29865): servidor escuchando puerto: 1234
05-08 20:09:39.588: W/System.err(29865): Conexión establecida con :192.168.0.102
05-08 20:09:39.598: I/System.out(29865): GET /sdcard/sodacachito.db HTTP/1.1
05-08 20:09:39.598: I/System.out(29865): Accept: */*
05-08 20:09:39.598: I/System.out(29865): Accept-Encoding: gzip, deflate
05-08
20:09:39.598: I/System.out(29865): User-Agent: Mozilla/4.0 (compatible;
MSIE 7.0; Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET
CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3;
.NET4.0C; .NET4.0E; Tablet PC 2.0)
05-08 20:09:39.598: I/System.out(29865): Host:
192.168.0.103:123405-08 20:09:39.598: I/System.out(29865): Connection: Keep-Alive
05-08 20:09:39.608: W/System.err(29865): ARCHIVO ENCONTRADO
y en el caso qçde que quiera abrir la base de datos me da este mensaje de error:SQLiteManager: Error in opening file sodacachito.db - either the file is encrypted or corrupt
Exception Name: NS_ERROR_FILE_CORRUPTED
Exception Message: Component returned failure code: 0x8052000b (NS_ERROR_FILE_CORRUPTED) [mozIStorageService.openUnsharedDatabase]