I've written a simple nodejs ws websocket server that is serving a binary jpeg file when a client connects as follows:
import WebSocket = require("ws");
console.log("Websocket is starting...");
// Setup websocket
const wss = new WebSocket.Server({ port: 8080 });
wss.on("connection", function connection(webSocket) {
console.log("Connected");
webSocket.on("message", function incoming(message) {
console.log("received: %s", message);
});
webSocket.on("error", function error(err) {
console.log(err.error);
});
webSocket.send(binaryJpegFile);
});
There was an error in this code as it sends as text by default so I replaced:
webSocket.send(binaryJpegFile);
with:
webSocket.send(binaryJpegFile, {binary: true});
Now my flutter codes receives the binary jpeg file as a Uint8List using the following code:
WebSocket socket;
void handleWebSocket(data) {
// Listen for incoming data. We expect the data to be a JSON-encoded String.
print("WebSocket data received");
if (data.runtimeType == String) {
print("String received");
String dataString = data;
print(dataString.length);
print(dataString);
} else if (data.runtimeType == Uint8List) {
print("Binary received");
Uint8List binaryIntList = data;
print(binaryIntList.lengthInBytes);
} else {
print("Unknown datatype recieved : " + data.runtimeType.toString());
}
}
connect() async {
if (socket == null) {
socket = await WebSocket.connect('ws://localhost:8080');
socket.listen(handleWebSocket);
}
socket.add('Hello, World!');
}
@override
void initState() {
super.initState();
connect();
}
Can anyone give tips on how to convert Uint8List to a jpeg file I can draw?