i am listening a socket connection and print data to debug console in vscode.
But, i could not get all data. For example; original data:" 123456789" received data: "1234"
How can i get all data without lossless ? Whats the wrong with my code. My code is below.
This is my first method;
void listenSocket() async {
final socket = await Socket.connect("10.0.0.3", 5000);
if (kDebugMode) {
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);
if (kDebugMode) {
print('Server: $serverResponse');
}
message = serverResponse;
},
// handle errors
onError: (error) {
if (kDebugMode) {
print(error);
}
socket.destroy();
},
// handle server ending connection
onDone: () {
if (kDebugMode) {
print('Server left.');
}
socket.destroy();
},
);
}
Please take my answer with caution since i am a beginner and this not my programming language, and it might be wrong. Am i right that you use TCP Protocol to transfer the data? If yes, then this could be your solution. TCP guarantees the undamaged data transfer in the right order, but it doesnt guarantee that if you say SEND, that it will actually send it in the chunck like you want. It might send a part, and then again a part. Or it might even send 2 "messages" in one go, without your intention. To solve this: You need a identifyer at the end of each message, something like: "&(/!!&€". If you receive that characters, you know its the end of a data chunck.
When you receive the messages, you add them to a Buffer.
Now you check if the buffer contains the EndOfMessage identifyer, if not you receive again.
Now you split the message at the identifyer in 2 parts, one is your CompleteMessage, the other is remainingData.
*some code that splits the Data into a array named temp, then:
Now you put the remaining data back into the Buffer.
Now you are sure completeDatamodel is indeed complete, and you can work with that.