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)