2013-06-23 3 views
1

Я создал небольшую клиентскую программу для Android. Он работает как шарм, кроме одного. Первый сеанс передачи файлов работает без каких-либо проблем, но когда я пытаюсь отправить другой файл, я не могу этого сделать, не перезапустив соединение сокета. Я хотел бы достичь этого: 1. Запустите Android-сервер 2. Подключите удаленный клиент 3. Перенесите столько файлов, сколько хотите в тот же сеанс (без перезапуска сервера и повторного подключения клиента) Как это сделать? Любая помощь будет оценена! Вот мой фрагмент кода: Серверные методы стороне:Я должен перезапустить соединение сокета Java для множественной передачи файлов

public void initializeServer() { 
    try { 
     serverSocket = new ServerSocket(4444); 
     runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        registerLog("Server started successfully at: "+ getLocalIpAddress()); 
        registerLog("Listening on port: 4444"); 
        registerLog("Waiting for client request . . ."); 
       } 
      }); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     Log.d("Listen failed", "Couldn't listen to port 4444"); 
    } 

    try { 
      socket = serverSocket.accept(); 
      runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         registerLog("Client connected: "+socket.getInetAddress()); 
        } 
       }); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     Log.d("Acceptance failed", "Couldn't accept client socket connection"); 
    } 
} 

Отправка файла клиенту:

public void sendFileDOS() throws FileNotFoundException { 
    runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       registerLog("Sending. . . Please wait. . ."); 
      } 
     }); 
    final long startTime = System.currentTimeMillis(); 
    final File myFile= new File(filePath); //sdcard/DCIM.JPG 
    byte[] mybytearray = new byte[(int) myFile.length()]; 
    FileInputStream fis = new FileInputStream(myFile); 
    BufferedInputStream bis = new BufferedInputStream(fis); 
    DataInputStream dis = new DataInputStream(bis); 
    try { 
     dis.readFully(mybytearray, 0, mybytearray.length); 
     OutputStream os = socket.getOutputStream(); 
     //Sending file name and file size to the server 
     DataOutputStream dos = new DataOutputStream(os);  
     dos.writeUTF(myFile.getName());  
     dos.writeLong(mybytearray.length);  
     dos.write(mybytearray, 0, mybytearray.length);  
     dos.flush(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       long estimatedTime = (System.currentTimeMillis() - startTime)/1000; 
       registerLog("File successfully sent"); 
       registerLog("File size: "+myFile.length()/1000+" KBytes"); 
       registerLog("Elapsed time: "+estimatedTime+" sec. (approx)"); 
       registerLog("Server stopped. Please restart for another session."); 
      } 
     }); 
} 

стороне клиента (работает на компьютере):

public class myFileClient { 
final static String servAdd="10.142.198.127"; 
static String filename=null; 
static Socket socket = null; 
static Boolean flag=true; 

/** 
* @param args 
*/ 
public static void main(String[] args) throws IOException { 
    // TODO Auto-generated method stub 
    initializeClient(); 
    receiveDOS();  
} 
public static void initializeClient() throws IOException { 
    InetAddress serverIP=InetAddress.getByName(servAdd); 
    socket=new Socket(serverIP, 4444); 
} 
public static void receiveDOS() { 
    int bytesRead; 
    InputStream in; 
    int bufferSize=0; 

    try { 
     bufferSize=socket.getReceiveBufferSize(); 
     in=socket.getInputStream(); 
     DataInputStream clientData = new DataInputStream(in); 
     String fileName = clientData.readUTF(); 
     System.out.println(fileName); 
     OutputStream output = new FileOutputStream("//home//evinish//Documents//Android//Received files//"+ fileName); 
     long size = clientData.readLong(); 
     byte[] buffer = new byte[bufferSize]; 
     while (size > 0 
       && (bytesRead = clientData.read(buffer, 0, 
         (int) Math.min(buffer.length, size))) != -1) { 
      output.write(buffer, 0, bytesRead); 
      size -= bytesRead; 
     } 

    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

ответ

1

Попробуйте промывке только после

output.write(buffer, 0, bytesRead); 

Если это все еще не работает, я обнаружил, что мой сервер/клиент работает лучше всего с objectoutputstream, которые вы используете следующим образом.

oos = new ObjectOutputStream(socket.getOutputStream()); 
ois = new ObjectInputStream(socket.getInputStream()); 

// always call flush and reset after sending anything 
oos.writeObject(server.getPartyMembersNames()); 
oos.flush(); 
oos.reset(); 

YourObject blah = (YourObject) ois.readObject(); 
+0

Большое спасибо! :) –

Смежные вопросы