【问题标题】:How to send image over socket connection?如何通过套接字连接发送图像?
【发布时间】:2021-03-08 15:53:13
【问题描述】:

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

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();
    },
  );
}

服务器端图像错误:

【问题讨论】:

    标签: sockets dart socket.io dart-pub


    【解决方案1】:

    只需在客户端将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 将对象转换为字符串。 祝你有美好的一天:)

    【讨论】:

    • 使用 socket.addStream 来自 stackvoerflow 上的另一个答案,它运行良好。谢谢:)
    猜你喜欢
    • 2013-12-31
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    相关资源
    最近更新 更多