在flutter中使用套接字编程将图像发送到服务器

Sending image to server using socket programming in flutter

我在 python 中有一个服务器端程序需要图像,并且在 python.

中使用客户端程序测试时工作正常

我想使用 flutter 将图像发送到此服务器,但我没有这样做..

这是我的服务器端代码

import socket       #server


server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # AF_INET = IP, SOCK_STREAM = TCP
server.bind(('localhost', 1112))  # 127.0.0.1
server.listen()

client_socket, client_address = server.accept()

file = open('2.jpg', "wb")
image_chunk = client_socket.recv(1024)  # stream-based protocol

while image_chunk:
    file.write(image_chunk)
    image_chunk = client_socket.recv(1024)

file.close()
client_socket.close()

我试过使用 diohttpMultiPart

以下是我失败尝试的片段:

  1. MultiPart

     var uri = Uri.parse('https://10.0.2.2:1112');
     var request = MultipartRequest('POST', uri)
       ..files.add(await MultipartFile.fromPath(
           'picture', filePath,
           contentType: MediaType('application', 'jpeg')));
     var response = await request.send();
     if (response.statusCode == 200) print('Uploaded!');
    
  2. Dio

    Dio dio = new Dio();
     FormData formData = new FormData.fromMap({
       "file": await MultipartFile.fromPath(filePath, filename: basename(filePath),
         contentType: MediaType('application', 'jpeg'),)
     });
    await dio.post('https://10.0.2.2:1112', data: formData);
    

我可以创建连接,但无法发送文件。

P.S: 我几乎没有使用套接字的经验,所以我卡在了这里。

由于您正在处理 websocket,因此您必须签出此包 web_socket_channel

您首先需要使用

与您的套接字通道建立连接
var channel = IOWebSocketChannel.connect(Uri.parse('ws://localhost:1234'));

要从您的 websocket 频道收听更改,您将使用:

 channel.stream.listen((message) {
    print("NEW MESSAGE");
  });

要将数据发送到您的 websocket 通道,您将使用:

channel.sink.add("your data");

最后,不要忘记使用以下方式关闭您的 websocket 通道流:

channel.sink.close();

问题是您正在尝试通过 HTTP 请求连接到套接字 api(不是 websocket,它们是不同的)并在 server-side 上期望获取图像字节,但这不会发生,因为如您所知,HTTP 有自己的规范 RFC2616。所以你会得到一些 http headers 和 body.

实际上您可以向套接字发送 http 请求,但在 server-side 上您必须完成繁重的工作。我的意思是逐行阅读 http header 然后阅读 Transfer-EncodingContent-Length header 以了解如何读取请求的剩余字节,然后解析 body数据。

The Content-Length entity header indicates the size of the entity-body, in bytes, sent to the recipient.

The Transfer-Encoding header specifies the form of encoding used to safely transfer the payload body to the user.

解决方案是:

  1. 在客户端使用 dart 套接字库,然后通过套接字而不是 http 请求发送图像(这 link 可能会有帮助)

  2. 或者创建一个 RESTFUL API 并像以前一样通过 http 请求发送您的图像。

希望能帮到你:)