2014-01-06 3 views
3

Какую услугу я должен определить для файла .thrift, чтобы использовать его позже для моей Программы?Файловый транспорт между сервером/клиентом

Этот файловый транспорт должен находиться между Клиентом и Сервером, и он должен быть «частично».

StreamFileService.thrift:

struct FileChunk { 
1: binary data 
2: i64 remaining 
} 

service StreamFileService {  
FileChunk getBytes(1:string fileName, 2: i64 offset, 3: i32 size);  
} 

StreamFileClient.java:

public class StreamFileClient { 
private int fileChunkSize = 16; 
private String filePath; 

public String getFilePath() { 
    return filePath; 
} 

public void setFilePath(String filePath) { 
    this.filePath = filePath; 
} 

private void invoke() { 

    try { 

     TTransport theClientTransport = new TFramedTransport(new TSocket(
       "127.0.0.1", 7911)); 
     TProtocol theProtocol = new TBinaryProtocol(theClientTransport); 
     StreamFileService.Client theClient = new StreamFileService.Client(
       theProtocol); 
     theClientTransport.open(); 

     filePath = "/home/output/output.pdf"; 
     File theFile2 = new File(filePath); 
     theFile2.createNewFile(); 
     FileInputStream stream = new FileInputStream(theFile2); 
     long currentPosition = 0; 

     FileChannel theFileChannel = stream.getChannel(); 
     boolean again = true; 

     do { 
      FileChunk chunk2 = theClient.getBytes(filePath, 
        currentPosition, fileChunkSize); 
      currentPosition += fileChunkSize; 

      theFileChannel.write(chunk2.data); 

      if (chunk2.remaining == 0) 
       again = false; 

     } while (again); 
     stream.close(); 

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

public static void main(String[] args) { 
    StreamFileClient theClient = new StreamFileClient(); 

    theClient.invoke(); 

} 

}

StreamFileServer.java:

public class StreamFileServer { 

private void start() { 
    try { 

     TNonblockingServerTransport theServerSocket = new TNonblockingServerSocket(
       7911); 
     StreamFileService.Processor theProcessor = new StreamFileService.Processor(
       new StreamFileServiceImpl()); 
     TServer theServer = new TNonblockingServer(
       new TNonblockingServer.Args(theServerSocket) 
         .processor(theProcessor)); 
     System.out.println("Server starting on port 7911..."); 

     theServer.serve(); 

    } catch (TTransportException e) { 
     e.printStackTrace(); 
    } 

} 

public static void main(String[] args) { 
    StreamFileServer theFileServer = new StreamFileServer(); 
    theFileServer.start(); 
} 

}

StreamFileServiceImpl:

public class StreamFileServiceImpl implements StreamFileService.Iface { 

public FileChunk getBytes(String filePath, long offset, int size) 
     throws TException { 

    File theFile = new File("/home/input/kl_12.pdf"); 
    FileChunk chunk = new FileChunk(); 

    try { 

     FileOutputStream stream = new FileOutputStream(theFile); 

     MappedByteBuffer buffer = stream.getChannel().map(
       FileChannel.MapMode.READ_ONLY, offset, size); 
     chunk.data = buffer; 
     chunk.remaining = stream.getChannel().size() - offset - size; 
     stream.close(); 

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

}

+0

Не могли бы вы попытаться улучшить свой вопрос? И что означает «отчасти»? А может быть, описать, что вы уже пробовали? В текущем формате вопрос, скорее всего, будет закрыт, а ответа не будет. – JensG

+0

Я пытаюсь реализовать Server-> Client - Filetransfer with Thrift. «Частично» означает не всю длину файла один раз для передачи, но дважды или три раза для передачи. – Dakatabe

+0

Это как моя служба выглядит (StreamFileService.thrift): ЬурейиЙ бинарного Бинар сервис StreamFileService { \t Бинар GetBytes (1: строка файла); \t } – Dakatabe

ответ

4

Ваш код выглядит не так уж плохо для меня (не проверял), и там не так много, чтобы изменить.

Как насчет

typedef binary binar 
service StreamFileService {  
    binar getBytes(1:string fileName, 2: i64 offset, 3: i32 size);  
    i64 getSize(1:string fileName) 
} 

Я также хотел бы вернуться на структуру, удерживающую байт, но это более или менее мое личное мнение.

struct FileChunk { 
    1: binary data 
    2: i64 remaining 
} 

service StreamFileService {  
    FileChunk getBytes(1:string fileName, 2: i64 offset, 3: i32 size);  
} 

FileChunk структура может быть легко расширена, если такое становится необходимым, например, чтобы возвращать дополнительные метаданные, такие как общий размер (особенно, если размер увеличивается/сокращается с течением времени), оставшиеся байты, указания относительно формата данных и т. п. Вам не обязательно это делать, поскольку вы можете легко расширить интерфейс, если это понадобится позже. Вопрос вкуса.

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