|
|
|
![]() |
|
Strumenti |
![]() |
#1 |
Senior Member
Iscritto dal: Oct 2003
Città: TV
Messaggi: 10831
|
[JAVA] - comunicazione http - migliorare il buffer
Ciao,
un esercizio, che non so da dove cominciare... Ho questo codice, avviato da un server http e fa certe semplici cose, cioè visualizzare una risorsa.. un file di testo o un immagine. E' molto grossolano, prende tutta la risorsa e la spedisce al client (il browser). Vorrei migliorarlo, nel senso che prenda piccole porzioni della risorsa richiesta e la trasferisca a pezzi più piccoli. ma come? Codice:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tinyhttpd; import java.net.*; import java.io.*; import java.util.*; /** * * @author autore */ class tinyhttpdconnection extends Thread { Socket sock; tinyhttpdconnection (Socket s) { sock = s; setPriority(NORM_PRIORITY -1); start(); } public void run() { try { OutputStream out = sock.getOutputStream(); BufferedReader in=new BufferedReader(new InputStreamReader(sock.getInputStream())); String req = in.readLine(); System.out.println( "Request: "+req ); StringTokenizer st = new StringTokenizer( req ); if ( (st.countTokens() >= 2) && st.nextToken().equals("GET") ) { if ( (req = st.nextToken()).startsWith("/") ) req = req.substring( 1 ); if ( req.endsWith("/") || req.equals("") ) req = req + "index.html"; try { FileInputStream fis = new FileInputStream ( req ); byte [] data = new byte [ fis.available() ]; fis.read( data ); out.write( data ); } catch ( FileNotFoundException e ) { new PrintStream( out ).println("404 Not Found"); } } else new PrintStream( out ).println( "400 Bad Request" ); sock.close(); } catch ( IOException e ) { System.out.println( "I/O error " + e ); } } }
__________________
cagnaluia MTB|DH|Running|Diving Eos1DX|16-35f4Lis|35f1.4L|100f2|300F4LIS |
![]() |
![]() |
![]() |
#2 |
Member
Iscritto dal: Nov 2002
Messaggi: 262
|
Intendi una cosa tipo questa??
Codice:
public void copyBuffer(InputStream iStream, OutputStream outStream, int bufferSize) throws IOException { // Allochi il buffer byte [] buffer = new byte[bufferSize]; // Usata per capire quanti byte sono stati letti dallo stream int bytesRead = 0; // Cicli fino alla fine dello stream // Come vedi nella var bytesRead ottieni il numero di byte letti dallo stream while( (bytesRead = iStream.read(buffer)) >0 ) { // Scrivi il buffer in base al numero di bytes letti outStream.write(buffer, 0, bytesRead); // Dopo le scritture fare un flush dello stream e' consigliato outStream.flush(); } } |
![]() |
![]() |
![]() |
#3 |
Senior Member
Iscritto dal: Oct 2003
Città: TV
Messaggi: 10831
|
si, perfetta.
__________________
cagnaluia MTB|DH|Running|Diving Eos1DX|16-35f4Lis|35f1.4L|100f2|300F4LIS |
![]() |
![]() |
![]() |
Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 21:50.