in Education by
I'm trying to create Server-client connection using sockets. Server is just an Echo-server. I want to send different types of data there. I've started with Images. What I want to achieve is : Parse image stored in the assets folder to appropriate data type Send it to Echo Server Receive data back on the mobile (client) site Display an image send that way (to be sure, data was send correctly) I've implemented both Client and Server. Client is in Flutter, Server in Ktor. Server implementation was copied from tutorial: https://ktor.io/servers/raw-sockets.html. What I can see, is that my server is receiving an image and sending it back correctly, but I am not able to show it. Server code : fun main() { runBlocking { val server = aSocket(ActorSelectorManager(Dispatchers.IO)).tcp().bind(InetSocketAddress("localhost", 8080)) println("Started echo telnet server at ${server.localAddress}") while (true) { val socket = server.accept() launch { println("Socket accepted: ${socket.remoteAddress}") val input = socket.openReadChannel() val output = socket.openWriteChannel(autoFlush = true) try { while (true) { val line = input.readUTF8Line() line?.let { println("Client sent: $line") output.writeStringUtf8(it) } } } catch (e: Throwable) { println("Closing socket") e.printStackTrace() socket.close() } } } } } and Client: class MyHomePage extends StatefulWidget { final String title; MyHomePage({Key key, @required this.title}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State { Socket _socket; List _connectionTimes = []; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ RaisedButton( child: const Text('Connect to socket'), color: Theme.of(context).accentColor, elevation: 4.0, onPressed: () { closeSocket(); _connectToSocket().then((createdSocket) { setState(() { _socket = createdSocket; }); }); }, ), RaisedButton( child: const Text('Send to socket'), color: Theme.of(context).accentColor, elevation: 4.0, onPressed: () { _sendMessage(); }, ), StreamBuilder( stream: _socket, builder: (context, snapshot) { if(snapshot.hasData) { final bytes = base64Decode(utf8.decode(snapshot.data)); return Image.memory(bytes); } else { return Text("no image"); } }, ), ], )), ); } Future _connectToSocket() async { final stopwatch = Stopwatch()..start(); Socket sock = await Socket.connect('10.0.2.2', 8080); print("Connection time was ${stopwatch.elapsedMilliseconds}"); return sock; } void _sendMessage() async{ final imageBytes = await rootBundle.load('assets/images/dog.jpeg'); final bytesAsString = base64Encode(imageBytes.buffer.asUint8List(imageBytes.offsetInBytes, imageBytes.lengthInBytes)); print(bytesAsString); _socket.write(bytesAsString+"\n"); } void closeSocket() { if (_socket != null) { _socket.close(); } } @override void dispose() { _socket.close(); super.dispose(); } } The error i receive is : E/flutter ( 8235): [ERROR:flutter/lib/ui/painting/codec.cc(97)] Failed decoding image. Data is either invalid, or it is encoded using an unsupported format. I/flutter ( 8235): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════ I/flutter ( 8235): The following _Exception was thrown resolving an image codec: I/flutter ( 8235): Exception: operation failed I/flutter ( 8235): ════════════════════════════════════════════════════════════════════════════════════════════════════ And in addition I have some more questions: Is there a better way to parse image from assets in Flutter? Is there a way to send this data without adding \n at the end of an image data? Is it possible that image would be too large, and I wouldn't be able to send it in one request? If yes, what should I change in code to make it work? Divide it to several calls and use buffer on both client and server? What should I change in server code, that would allow me to run it once, and connect and disconnect with single client multiple times? (It's annoying, that with every change I make to the Flutter code, I have to rerun server so it works correctly? I'm open for changing server implementation to another framework / language. I want to use Flutter, but it doesn't have to be Ktor on Server site. Just wanted to check it in action. JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by
I am able to use the following code to Read a jpg image from the photo gallery, send to a node.js server by socket.io, then transfer to another client(at the same time save the image in mysql, just like whatsapp send image) String base64Image1 = ''; // strImage1 is the path of the photo gallery retrieved by the plugin path_provider, plus the file name of the image. String strImage1 = gv.strHomeImageFileWithPath + '_01.jpg'; var filImage1 = new File(strImage1); List imageBytes1 = filImage1.readAsBytesSync(); // use the following line if another client wants to display this image in html // base64Image1 = 'data:image/jpg;base64,' + base64Encode(imageBytes1); // Or, use the following line if another client wants to display this image in flutter base64Image1 = base64Encode(imageBytes1); // Send the b64 image string to the server gv.socket.emit('PIBRequestPhotoClassify', [base64Image1]); It seems that my codes to decode and display the b64 image string is the same as yours, but the codes to encode the image is different, pls. try.

Related questions

0 votes
    Which value of Socket.readyState atribute of WebSocket indicates that the connection is going through the closing handshake? A - 0 B - 1 C - 2 D - 3...
asked Dec 2, 2020 in Technology by JackTerrance
0 votes
    The idea is to create server in master process, and handle requests in workers. I want to utilize all ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Jan 15, 2022 in Education by JackTerrance
0 votes
    I have troubles with socket connection of PC (simple server written on Java) and android emulator. ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 19, 2022 in Education by JackTerrance
0 votes
    I have troubles with socket connection of PC (simple server written on Java) and android emulator. ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 19, 2022 in Education by JackTerrance
0 votes
    I have troubles with socket connection of PC (simple server written on Java) and android emulator. ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 18, 2022 in Education by JackTerrance
0 votes
    I've tried to test socket connection in Java, but failed. Here is my code (two simple applications, ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 18, 2022 in Education by JackTerrance
0 votes
    I've tried to test socket connection in Java, but failed. Here is my code (two simple applications, ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 16, 2022 in Education by JackTerrance
0 votes
    I have troubles with socket connection of PC (simple server written on Java) and android emulator. ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 16, 2022 in Education by JackTerrance
0 votes
    Which value of Socket.readyState atribute of WebSocket indicates that the connection has been closed or could not be opened? A - 0 B - 1 C - 2 D - 3...
asked Dec 2, 2020 in Technology by JackTerrance
0 votes
    Which value of Socket.readyState atribute of WebSocket indicates that the connection is established and communication is possible? A - 0 B - 1 C - 2 D - 3...
asked Dec 2, 2020 in Technology by JackTerrance
0 votes
    Which value of Socket.readyState atribute of WebSocket indicates that the connection has not yet been established? A - 0 B - 1 C - 2 D - 3...
asked Dec 2, 2020 in Technology by JackTerrance
0 votes
    I was trying to write a quick-and-dirty script to generate plots easily. For that, I was using the following code ( ... do I do that? Select the correct answer from above options...
asked Jan 30, 2022 in Education by JackTerrance
0 votes
    I am adding an background image to the Splash screen, but is not rendering the image. Sometime it load ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Jun 2, 2022 in Education by JackTerrance
0 votes
    I searched a lot about this but I didn't find anywhere. There are a few APIs, but all of them ... , JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 6, 2022 in Education by JackTerrance
0 votes
    _____________ are implemented to carry out distributed DDoS attacks, steal data, send spam messages & permits ... Cyber Security:,Cyber Security-Jobs:,Cyber Security Applications...
asked Nov 1, 2021 in Education by JackTerrance
...