如何通过套接字连接发送图像? [英] How to send image over socket connection?

查看:107
本文介绍了如何通过套接字连接发送图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying to send image over socket connection from client to server which will be saved on the server.

套接字连接可以很好地处理 string 消息,但是当我尝试发送图像时,它无法正确传输.请给我一个提示,看看做对的方法是正确的.

The socket connection works fine for string messages but when I try to send an image, it is not transmitted correctly. Please give me a clue on what's the right way to do it.

服务器端代码:

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),一面,你很好走

Just change socket.write(message) to socket.add(message) at the client-side and you are good to go

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

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

because socket.write(object) Converts object to a String by invoking Object.toString. have a nice day:)

这篇关于如何通过套接字连接发送图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆