CERCA
PER MODELLO
FullScreen Chatbox! :)

Utente del giorno: megthebest con ben 1 Thanks ricevuti nelle ultime 24 ore
Utente della settimana: carotix con ben 4 Thanks ricevuti negli ultimi sette giorni
Utente del mese: megthebest con ben 21 Thanks ricevuti nell'ultimo mese

Visualizzazione dei risultati da 1 a 6 su 6
Discussione:

problema nella ricezione di file dal server

Se questa discussione ti è stata utile, ti preghiamo di lasciare un messaggio di feedback in modo che possa essere preziosa in futuro anche per altri utenti come te!
  1. #1
    Androidiano


    Registrato dal
    Sep 2010
    Messaggi
    53

    Ringraziamenti
    0
    Ringraziato 0 volte in 0 Posts
    Predefinito

    problema nella ricezione di file dal server

    Buongiorno ragazzi.
    Sto tendando di ricevere due file provenienti da un server al mio client android (l'SDK per ora).
    Il processo inverso cioè l'invio di un file dal client android al server funziona alla perfezione.
    Quello che volevo fare ora è andare a ricevere dal server due file e salvarli sulla sd virtuale dell'sdk.
    Questo è il mio server:
     
    1
    2
    long start = System.currentTimeMillis();
    3
                        int bytesRead;
    4
                        int current = 0;
    5
    6
                     
    7
                      Socket client = serverSocket.accept();
    8
                      System.out.println("S: Receiving to client...");
    9
             
    10
                      try {
    11
                         
    12
                              BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    13
                          String str = in.readLine();
    14
                          System.out.println("S: Received: '" + str + "'");
    15
                         
    16
                         
    17
                          //RICEZIONE NELLA CARTELLA DI LAVORO DEL FILE QUANTITATOSERVER.xml DAL
    18
                          //DISPOSITIVO MOBILE
    19
                          byte [] mybytearray  = new byte [filesize];
    20
                          InputStream is = client.getInputStream();
    21
                          FileOutputStream fos = new FileOutputStream("QUANTITATOSERVER.xml");
    22
                          BufferedOutputStream bos = new BufferedOutputStream(fos);
    23
                          bytesRead = is.read(mybytearray,0,mybytearray.length);
    24
                          current = bytesRead;
    25
    26
                          do {
    27
                             bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
    28
                             if(bytesRead >= 0) current += bytesRead;
    29
                          } while(bytesRead > -1);
    30
    31
                          bos.write(mybytearray, 0 , current);
    32
                          bos.flush();
    33
                          long end = System.currentTimeMillis();
    34
                          System.out.println(end-start);
    35
                          bos.close();
    36
                         
    37
       
    38
                       
    39
                            //INVIO AL DISPOSITIVO MOBILE DEL FILE ARTICOLI.XML
    40
                         
    41
                                File myArticoli = new File ("articoli.xml");
    42
                                    FileInputStream fis = new FileInputStream(myArticoli);
    43
                                    BufferedInputStream bis = new BufferedInputStream(fis);
    44
                                    byte [] mybytearray3 = new byte [(int)myArticoli.length()];
    45
                                    bis.read(mybytearray3,0,mybytearray3.length);
    46
                                    OutputStream os = client.getOutputStream();
    47
                                    os.write(mybytearray3,0, mybytearray3.length);
    48
                                    os.flush();
    49
                         
    50
                            //INVIO AL DISPOSITIVO MOBILE DEL FILE LOGSPESA.XML CON
    51
                            //LE QUANTITA CORRETTAMENTE AGGIORNATE
    52
                           
    53
                            File myLogspesa = new File ("logspesa.xml");
    54
                            FileInputStream fis2 = new FileInputStream(myLogspesa);
    55
                            BufferedInputStream bis2 = new BufferedInputStream(fis2);
    56
                            byte [] mybytearray2 = new byte [(int)myLogspesa.length()];
    57
                            bis2.read(mybytearray2,0,mybytearray2.length);
    58
                           OutputStream os2 = client.getOutputStream();
    59
                                    os2.write(mybytearray2,0, mybytearray2.length);
    60
                                    os2.flush();
    61
                         
    62
    63
                        } catch(Exception e) {
    64
                            System.out.println("S: Error");
    65
                            e.printStackTrace();
    66
                        } finally {
    67
                            client.close();
    68
                            System.out.println("S: Done.");
    69
                        }
    70
    71
                 }
    72
                 
    73
             } catch (Exception e) {
    74
                 System.out.println("S: Error");
    75
                 e.printStackTrace();
    76
             }
    77
        }//FINE CLASSE RUN
    78
       
    79
        //MAIN
    80
        public static void main (String a[]) throws SQLException, ClassNotFoundException {
    81
           
    82
            try{
    83
                           
    84
                    invioFileXMLtoAndroid();
    85
                   
    86
                    }catch(IOException ex){
    87
                            ex.printStackTrace();
    88
                    }
    89
           
    90
            Thread desktopServerThread = new Thread(new TCPDesktopServer());
    91
            desktopServerThread.start();
    92
    93
        } //Fine MAIN
    94
       
    95
       
    96
       
    97
    static public void invioFileXMLtoAndroid() throws IOException, SQLException, ClassNotFoundException{
    98
                   
    99
                    XmlWriter xmlwriterArt  = new XmlWriter(new     java.io.FileWriter("articoli.xml"));
    100
                XmlWriter xmlwriterLog      = new XmlWriter(new     java.io.FileWriter("logspesa.xml"));
    101
                   
    102
                    Vector<ArticoloBean> VetArt = ArticoloDB.getAllArticolo(DBConnection.getBDConnection().getConnection());
    103
                    Vector<LogSpesaBean> VetLog = LogSpesaDB.getLogSpesa(DBConnection.getBDConnection().getConnection(),CalendarUtility.getTodayLong());           
    104
                   
    105
    106
                    for(int j=0; j<VetArt.size(); j++)
    107
                            {
    108
                                    xmlwriterArt.writeObject(VetArt.elementAt(j));
    109
                            }
    110
                    xmlwriterArt.close();
    111
                   
    112
                   
    113
                   
    114
                    for(int j=0; j<VetLog.size(); j++)
    115
                            {
    116
                                    xmlwriterLog.writeObject(VetLog.elementAt(j));
    117
                            }
    118
                    xmlwriterLog.close();
    119
                   
    120
           
    121
            } //Fine classe invioFileXMLtoAndroid()
    122
       
    123
    } //Fine public class TCPDesktopServer implements Runnable
    124

  2.  
  3. #2
    Androidiano


    Registrato dal
    Sep 2010
    Messaggi
    53

    Ringraziamenti
    0
    Ringraziato 0 volte in 0 Posts
    Predefinito

    e questa è la mia classe client:
    107
     
    1
    2
    public class TCPClient implements Runnable {
    3
    4
           
    5
        public void run() {
    6
             try {
    7
                     
    8
                     InetAddress serverAddr = InetAddress.getByName("192.168.0.107");//TCPServer.SERVERIP
    9
                     
    10
                     Log.d("TCP", "C: Connecting to server...");
    11
                     //Socket socket = new Socket(serverAddr, TCPDesktopServer.SERVERPORT);
    12
                     Socket socket = new Socket(serverAddr, 4444);
    13
                     String message = "CONNESSIONE CON IL SERVER AVVENUTA!";
    14
                         try {
    15
                             
    16
                             Log.d("TCP", "C: Sending: '" + message + "'");
    17
                             PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
    18
                             out.println(message);
    19
                           
    20
                             
    21
                             //INVIO AL SERVER DEL FILE QUANTITATOSERVER CON IL QUALE SI AGGIORNERA' LA
    22
                             //TABELLA DISPENSA SUL DATABASE ANFASS
    23
                         File myFile = new File ("mnt/sdcard/QUANTITATOSERVER.xml");
    24
                         FileInputStream fis = new FileInputStream(myFile);
    25
                         BufferedInputStream bis = new BufferedInputStream(fis);
    26
                         byte [] mybytearray = new byte [(int)myFile.length()];
    27
                         bis.read(mybytearray,0,mybytearray.length);
    28
                         OutputStream os = socket.getOutputStream();
    29
                         os.write(mybytearray,0, mybytearray.length);
    30
                         os.flush();
    31
                     
    32
                         
    33
                         int filesize=6022386; // filesize temporary hardcoded
    34
    35
                         long startARTICOLI = System.currentTimeMillis();
    36
                         int bytesReadARTICOLI;
    37
                         int currentARTICOLI = 0;
    38
                         
    39
                         //long startLOGSPESA = System.currentTimeMillis();
    40
                         //int bytesReadLOGSPESA;
    41
                         //int currentLOGSPESA = 0;
    42
                         
    43
                         
    44
                         //RICEZIONE DAL SERVER DEL FILE ARTICOLI.XML
    45
                         
    46
                         byte [] mybytearrayARTICOLI  = new byte [filesize];
    47
                     InputStream isAR = socket.getInputStream();
    48
                     FileOutputStream fosAR = new FileOutputStream("mnt/sdcard/articoli.xml");
    49
                     BufferedOutputStream bosAR = new BufferedOutputStream(fosAR);
    50
                     bytesReadARTICOLI = isAR.read(mybytearrayARTICOLI,0,mybytearrayARTICOLI.length);
    51
                     currentARTICOLI = bytesReadARTICOLI;
    52
    53
                     do {
    54
                        bytesReadARTICOLI = isAR.read(mybytearrayARTICOLI, currentARTICOLI, (mybytearrayARTICOLI.length-currentARTICOLI));
    55
                        if(bytesReadARTICOLI >= 0) currentARTICOLI += bytesReadARTICOLI;
    56
                     } while(bytesReadARTICOLI > -1);
    57
    58
                     bosAR.write(mybytearrayARTICOLI, 0 , currentARTICOLI);
    59
                     bosAR.flush();
    60
                     long endAR = System.currentTimeMillis();
    61
                     System.out.println(endAR-startARTICOLI);
    62
                     bosAR.close();
    63
                     
    64
                     
    65
                     
    66
                         //RICEZIONE DAL SERVER DEL FILE LOGSPESA.XML
    67
                     /*
    68
                     byte [] mybytearrayLOGSPESA  = new byte [filesize];
    69
                     InputStream isLS = socket.getInputStream();
    70
                     FileOutputStream fosLS = new FileOutputStream("mnt/sdcard/logspesa.xml");
    71
                     BufferedOutputStream bosLS = new BufferedOutputStream(fosLS);
    72
                     bytesReadLOGSPESA = isLS.read(mybytearrayLOGSPESA,0,mybytearrayLOGSPESA.length);
    73
                     currentLOGSPESA = bytesReadLOGSPESA;
    74
    75
                     do {
    76
                        bytesReadLOGSPESA = isLS.read(mybytearrayLOGSPESA, currentLOGSPESA, (mybytearrayLOGSPESA.length-currentLOGSPESA));
    77
                        if(bytesReadLOGSPESA >= 0) currentLOGSPESA += bytesReadLOGSPESA;
    78
                     } while(bytesReadLOGSPESA > -1);
    79
    80
                     bosLS.write(mybytearrayLOGSPESA, 0 , currentLOGSPESA);
    81
                     bosLS.flush();
    82
                     long endLS = System.currentTimeMillis();
    83
                     System.out.println(endLS-startLOGSPESA);
    84
                     bosLS.close();
    85
                         
    86
                         */
    87
                         
    88
                         
    89
                         
    90
                         
    91
                         Log.d("TCP", "C: Sent.");
    92
                         Log.d("TCP", "C: Done. DATI INVIATI!");
    93
                         
    94
                         
    95
                         
    96
                         
    97
                 } catch(Exception e) {
    98
                     Log.e("TCP", "S: Error", e);
    99
                          } finally {
    100
                            socket.close();
    101
                          }
    102
             } catch (Exception e) {
    103
                  Log.e("TCP", "C: Error", e);
    104
             }
    105
        }
    106
    }
    107


    Per ora sul client sto cercando di andare a salvarmi su sd solo il file articoli.xml ricevuto dal server ma quello che accade che in sd
    ho un file articoli.xml vuoto e non riesco a capire come mai...
    vi ringrazio ciao...


    nel LOGCAT a volte ho il seguente errore:
    11-13 14:43:46.679: ERROR/TCP(3678): S: Error
    11-13 14:43:46.679: ERROR/TCP(3678): java.lang.ArrayIndexOutOfBoundsException: Offset out of bounds : -1
    11-13 14:43:46.679: ERROR/TCP(3678): at org.apache.harmony.luni.net.SocketInputStream.read (SocketInputStream.java:82)
    11-13 14:43:46.679: ERROR/TCP(3678): at ch.egsolutions.databasetutorial.TCPClient.run(TCPC lient.java:71)
    11-13 14:43:46.679: ERROR/TCP(3678): at java.lang.Thread.run(Thread.java:1096)

  4. #3
    Baby Droid


    Registrato dal
    Dec 2010
    Messaggi
    3

    Ringraziamenti
    0
    Ringraziato 0 volte in 0 Posts
    Predefinito

    ciao senti hai risolto il tuo problema?? io ne ho uno simile.. nel senso che devo inviare una stringa xml ad un web server... il fatto del mio problema è che se devo ricevere la stessa stringa dal web server mi arriva quando faccio la richiesta post tramite outputstream mi da un errore lato server del genere :
    Error on line -1 of document : Premature end of file. Nested exception: Premature end of file.
    ho debuggato lato server e ho visto che il body del messaggio che arriva da android è null... non so se ci sono particolari problemi con outputstream visto che provado lo stesso codice al di fuori da android il tutto funziona... mi serve una mano urgente perchè devo terminare questo programma per un esame all'università!!! Grazie

  5. #4
    Androidiano


    Registrato dal
    Sep 2010
    Messaggi
    53

    Ringraziamenti
    0
    Ringraziato 0 volte in 0 Posts
    Predefinito

    Ciao.
    Il mio problema l'ho risolto.
    Riesco ad inviare file ad un client android e a salvarli sulla sd, dopo che il client android (il telefono) stesso invia una stringa al server del tipo "INVIAMI IL FILE EXAMPLE.XML".
    Il server la interpreta ed esegue il relativo thread.

    Questo è quello che faccio lato server:
    63
     
    1
    2
    public class TCPDesktopServer implements Runnable{
    3
        
    4
        public static final int SERVERPORT = 4444;
    5
        
    6
        public void run() {
    7
             try {
    8
                 System.out.println("SERVER: Connecting...");
    9
                  
    10
                 ServerSocket serverSocket = new ServerSocket(SERVERPORT);
    11
                 while (true) {
    12
                      
    13
                        int filesize=60223866; // filesize temporary hardcoded
    14
                        long start = System.currentTimeMillis();
    15
                        int bytesRead;            
    16
                        int current = 0;
    17
    18
                      Socket client = serverSocket.accept();
    19
                      System.out.println("S: Receiving to client...");
    20
          
    21
                      try {
    22
                          
    23
                          BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    24
                          String str = in.readLine();
    25
                          //System.out.println(str);
    26
                          
    27
                        
    28
                          
    29
                         if("INVIAMI IL FILE ARTICOLI.XML".equals(str)){
    30
                          System.out.println("S: CLIENT DICE: '" + str + "'");
    31
                            // Server che invia il file articoli.xml
    32
                            DataOutputStream outArt = new DataOutputStream(client.getOutputStream());
    33
                            FileInputStream inArt = new FileInputStream("articoli.xml");
    34
                            byte bufferArt[] = new byte[1024];
    35
                            System.out.println( "Invio file in corso articoli.xml..." );
    36
                            int iArt;
    37
                            while((iArt = inArt.read(bufferArt,0,bufferArt.length)) != -1){
    38
                            outArt.write(bufferArt,0,iArt);
    39
                            outArt.flush();
    40
                            }
    41
                            inArt.close();
    42
                            System.out.println( "Invio completato." );                    
    43
                         }
    44
                          
    45
                         
    46
                         if("INVIAMI IL FILE LOGSPESA.XML".equals(str)){
    47
                             System.out.println("S: CLIENT DICE: '" + str + "'");
    48
                           //Server che invia il file logspesa.xml
    49
                            DataOutputStream outLog = new DataOutputStream(client.getOutputStream());
    50
                            FileInputStream inLog = new FileInputStream("logspesa.xml");
    51
                            byte bufferLog[] = new byte[1024];
    52
                            System.out.println( "Invio file in corso logspesa.xml..." );
    53
                            int iLog;
    54
                            while((iLog = inLog.read(bufferLog,0,bufferLog.length)) != -1){
    55
                            outLog.write(bufferLog,0,iLog);
    56
                            outLog.flush();
    57
                            }
    58
                            inLog.close();
    59
                            System.out.println( "Invio completato." );
    60
                            }
    61
                         ............
    62
                         .............
    63


    Lato android mi sono creato un thread che poi nell'activity chiamo.
    E' il seguente:
    51
     
    1
    2
     public void run() {
    3
    4
             try {
    5
                 //rlabgw0.unipv.it:888
    6
                 InetAddress serverAddr = InetAddress.getByName("192.168.0.107");//TCPServer.SERVERIP
    7
                 
    8
                 Log.d("TCP", "C: Connecting to server...");
    9
                 //Socket socket = new Socket(serverAddr, TCPDesktopServer.SERVERPORT);
    10
                 Socket socket = new Socket(serverAddr, 4444); 
    11
                 String message = "INVIAMI IL FILE ARTICOLI.XML";
    12
                     
    13
                 try {
    14
                     
    15
                     Log.d("TCP", "CLIENT: Sending: '" + message + "'");
    16
                     PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
    17
                     out.println(message);
    18
                            
    19
                     System.out.println("Ricezione file in corso articoli.xml..");
    20
                     DataInputStream inArt = new DataInputStream(socket.getInputStream());
    21
                     File sdcardDirArt = Environment.getExternalStorageDirectory();
    22
                     File myFileArt = new File(sdcardDirArt,"articoli.xml");
    23
                     FileOutputStream outArt = new FileOutputStream(myFileArt);
    24
                     byte bufferArt[] = new byte[1024];
    25
                     int iArt;
    26
                     while ((iArt = inArt.read(bufferArt,0,bufferArt.length)) != -1){
    27
                     System.out.println("ci sono");
    28
                     outArt.write(bufferArt,0,iArt);
    29
                     }
    30
                     outArt.flush();
    31
                     outArt.close();
    32
                     System.out.println( "Ricezione completata!" );
    33
    34
                     Log.d("TCP", "C: Sent.");
    35
                     Log.d("TCP", "C: Done. DATI INVIATI!");
    36
                            
    37
                 } catch(Exception e) {
    38
                     Log.e("TCP", "S: Error", e);
    39
                  } finally {
    40
                    socket.close();
    41
                 
    42
                  }
    43
             } catch (Exception e) {
    44
                  Log.e("TCP", "C: Error", e);
    45
             }
    46
    47
            
    48
        }//chiusura metodo run 
    49
        
    50
    }//chiusura public class TCPClient implements Runnable
    51


    In questo modo funziona tutto alla perfezione.
    In pratica è una sorta di protocollo di comunicazione tra client e server.
    La tua eccezione mi suona strana. Non mi è mai capitata...prova a vedere il mio codice poi fammi sapere...io sarò di rientro a casa per le 17.30 quindi prima non potrò rispondere.
    ciao

  6. #5
    Baby Droid


    Registrato dal
    Dec 2010
    Messaggi
    3

    Ringraziamenti
    0
    Ringraziato 0 volte in 0 Posts
    Predefinito

    grazie provo con il printWriter vediamo che cosa succede.. grazie mille...

  7. #6
    Baby Droid


    Registrato dal
    Dec 2010
    Messaggi
    3

    Ringraziamenti
    0
    Ringraziato 0 volte in 0 Posts
    Predefinito

    ciao scusami ancora ma non riesco a farlo funzionare.. ti spiego quello che devo fare nel caso mi potresti dare una mano.. allora io ho da una parte un web server DAL che praticamente accetta una stringa xml, (tipo per esempio prodotti, clienti, fornitori..)se devo leggere dal web server il tutto funziona benissimo, quindi riesco a reperire i prodotti presenti al suo interno se da android mi creo un nuovo prodotto e quindi un nuovo xml quando lo vado a postare mi dice lato server:
    Error on line -1 of document : Premature end of file. Nested exception: Premature end of file.
    ho trovato la servlet che gestisce lo stream in input lato server e mi sono fatto stampare il flusso di dati che dovrebbe arrivare... STAMPA null.. a sto punto penso che da android non venga inviato bene la stringa.. ti posto sotto i metodi che fanno il post:

    public static void doContentRequest(String wsPart, String content, int expectedResponse,
    String expectedContent, String method,String user,String paswd) throws Exception {
    try {
    final HttpURLConnection hc = createConnection(wsPart, method,user,paswd);
    final OutputStream os = hc.getOutputStream();

    byte [] tmp=content.getBytes();
    for(int i=0;i<tmp.length;i++){
    System.out.println("tpm["+i+"]="+Byte.toString(tmp[i]));
    }
    os.write(content.getBytes("UTF-8"));
    os.flush();
    os.close();
    hc.connect();

    hc.getResponseCode();


    } catch (final Exception e) {
    //Log.i("Entra in err","errore");
    throw new Exception(e);
    }

    protected static HttpURLConnection createConnection(String wsPart, String method,final String LOGIN,final String PWD) throws Exception {
    Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(LOGIN, PWD.toCharArray());
    }
    });
    //log.debug(method + ": " + getOpenbravoURL() + wsPart);
    final URL url = new URL(baseUrl + wsPart);
    final HttpURLConnection hc = (HttpURLConnection) url.openConnection();

    hc.setRequestMethod(method);
    hc.setAllowUserInteraction(false);
    hc.setDefaultUseCaches(false);
    hc.setDoOutput(true);
    hc.setDoInput(true);
    hc.setInstanceFollowRedirects(true);
    hc.setUseCaches(false);
    hc.setRequestProperty("Content-Type", "text/xml");


    return hc;
    }

    }

    allora questi due metodi provati al di fuori da android vanno benissimo...
    se eseguo l'activiti non va un tubo!!! secondo te??? cosa potrei fare?? come risolvere?? sono bloccato è un progetto per il mio ultimo esame all'universtà... grazie mille!!

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire risposte
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Torna su
Privacy Policy