如何通过套接字连接发送图像?

How to send image over socket connection?

我一直在尝试通过套接字连接从客户端向服务器发送图像,这些图像将保存在服务器上。

string 消息的套接字连接工作正常,但是当我尝试发送图像时,它没有正确传输。请告诉我正确的方法是什么。

服务器端代码:

import 'dart:io';
import 'dart:typed_data';

void main() async {
  Uint8List bytes= await File('1.jpg').readAsBytes();
  
  
  final socket = await Socket.connect('localhost', 8000);
  print('Connected to: ${socket.remoteAddress.address}:${socket.remotePort}');

  // listen for responses from the server
  socket.listen(

    // handle data from the server
    (Uint8List data) {
      final serverResponse = String.fromCharCodes(data);
      print('Server: $serverResponse');
    },

    // handle errors
    onError: (error) {
      print(error);
      socket.destroy();
    },

    // handle server ending connection
    onDone: () {
      print('Server left.');
      socket.destroy();
    },
  );

  // send some messages to the server
  await sendMessage(socket, bytes);
  
}

Future<void> sendMessage(Socket socket, Uint8List message) async {
  print('Client: $message');
  socket.write(message);
}

客户端代码:

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:image/image.dart';
void main() async {
  // bind the socket server to an address and port
  final server = await ServerSocket.bind('127.0.0.1', 8000);

  // listen for clent connections to the server
  server.listen((client) {
    handleConnection(client);
  });
}

void handleConnection(Socket client) {
  print('Connection from'
      ' ${client.remoteAddress.address}:${client.remotePort}');

  // listen for events from the client
  client.listen(

    // handle data from the client
    (Uint8List data) async {
      // final message = String.fromCharCodes(data);
 
      print(data);
      await File('new.jpg').writeAsBytes(data);
    },

    // handle errors
    onError: (error) {
      print(error);
      client.close();
    },

    // handle the client closing the connection
    onDone: () {
      print('Client left');
      client.close();
    },
  );
}

服务器端图像错误:

只需在客户端将 socket.write(message) 更改为 socket.add(message) 就可以了

Future<void> sendMessage(Socket socket, Uint8List message) async {
 print('Client: $message');
 socket.add(message);
 }

因为 socket.write(object) 通过调用 Object.toString 将对象转换为字符串。 祝你有美好的一天:)