Android grpc java 传输文件demo
时间: 2024-02-17 07:00:40 浏览: 180
下面是一个简单的 Android gRPC Java 传输文件的演示,其中包括客户端和服务器端的代码。
1. 客户端代码
```java
public class FileTransferClient {
private ManagedChannel channel;
private FileTransferServiceGrpc.FileTransferServiceBlockingStub blockingStub;
public FileTransferClient(String host, int port) {
channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
blockingStub = FileTransferServiceGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public void uploadFile(File file) {
try {
FileInputStream inputStream = new FileInputStream(file);
StreamObserver<FileChunk> responseObserver = blockingStub.uploadFile(new StreamObserver<UploadStatus>() {
@Override
public void onNext(UploadStatus value) {
Log.d("FileUpload", "Upload status: " + value.getStatus());
}
@Override
public void onError(Throwable t) {
Log.e("FileUpload", "Upload error: " + t.getMessage());
}
@Override
public void onCompleted() {
Log.d("FileUpload", "Upload completed");
}
});
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
FileChunk fileChunk = FileChunk.newBuilder()
.setData(ByteString.copyFrom(buffer, 0, bytesRead))
.build();
responseObserver.onNext(fileChunk);
}
responseObserver.onCompleted();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 服务器端代码
```java
public class FileTransferServer {
private static final Logger logger = Logger.getLogger(FileTransferServer.class.getName());
private Server server;
public void start(int port) throws IOException {
server = ServerBuilder.forPort(port)
.addService(new FileTransferServiceImpl())
.build()
.start();
logger.info("Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("*** Shutting down gRPC server since JVM is shutting down");
FileTransferServer.this.stop();
System.err.println("*** Server shut down");
}
});
}
private void stop() {
if (server != null) {
server.shutdown();
}
}
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
final FileTransferServer server = new FileTransferServer();
server.start(50051);
server.blockUntilShutdown();
}
static class FileTransferServiceImpl extends FileTransferServiceGrpc.FileTransferServiceImplBase {
private FileOutputStream outputStream;
@Override
public StreamObserver<FileChunk> uploadFile(StreamObserver<UploadStatus> responseObserver) {
outputStream = null;
try {
outputStream = new FileOutputStream("path_to_save_file"); // 修改为你想要保存文件的路径
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new StreamObserver<FileChunk>() {
@Override
public void onNext(FileChunk value) {
try {
outputStream.write(value.getData().toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onCompleted() {
try {
outputStream.flush();
outputStream.close();
UploadStatus uploadStatus = UploadStatus.newBuilder()
.setStatus("Success")
.build();
responseObserver.onNext(uploadStatus);
responseObserver.onCompleted();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
}
}
```
这个示例演示了如何使用 gRPC 在 Android 上上传文件。在客户端代码中,我们创建了一个 `FileTransferClient` 类,它包含了与服务器通信的代码。在服务器端代码中,我们创建了一个 `FileTransferServer` 类,它包含了接收上传文件的代码。文件被分成块,并逐个发送到服务器。在服务器端,每个块被写入文件,直到接收到所有的块。在客户端,我们会收到上传的状态,包括上传是否成功以及错误信息。
阅读全文