简体   繁体   English

如何在Dart中通过套接字发送文件

[英]How to send file over a socket in Dart

I am trying to send a binary file like image or pdf over a socket. 我正在尝试通过套接字发送二进制文件,如图像或pdf。 I have tried following: 我尝试了以下方法:

   file.readAsBytesSync().forEach((f) {
     socket.write(f);
   });

And

   socket.write(file.readAsBytesSync());

But I receive a list of integers instead of a binary file. 但是我收到的是整数列表,而不是二进制文件。 Code given below in JAVA works fine and receiving port gets file in correct format JAVA中以下给出的代码可以正常工作,并且接收端口以正确的格式获取文件

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];

while (fis.read(buffer) > 0) {
    dos.write(buffer);
}

fis.close();
dos.close();

I am trying to figure out what would be Dart equivalent of above java code. 我试图弄清楚什么等同于上述Java代码的Dart。

Thanks in advance. 提前致谢。

Correct code: 正确的代码:

Socket s = await Socket.connect(host, port);
await s.addStream(file.openRead());
print("ok: data written");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM