Flutter Websocket giving feedback as NULL problem - flutter

Hello,
I am working with a login that works with websocket, when I send the correct parameters, the login connection is provided.It doesn't return me a statuscode 201 style message even if the connection is established.When I enter it wrong on purpose, it returns me this as an errorWebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'the url i entered#' was not upgraded to websocket the code is like this;
IOWebSocketChannel channel = new IOWebSocketChannel.connect("THE URL I ENTERED",headers: {"USER_ID":widget.user,"PASSWORD":widget.password},);
channel.stream.listen(
(dynamic message) {
debugPrint('message $message');
channel.sink.close(status.goingAway);
print(status.goingAway);
},
onDone: () {
debugPrint('ws channel closed');
},
onError: (error) {
print('socket closed: reason=[${channel.closeReason}], code:[${channel.closeCode}]');
debugPrint('ws error $error');
},
);
message i get in terminal
I/flutter ( 5598): socket closed: reason=[null], code:[null]
I/flutter ( 5598): ws error WebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'THE URL I ENTERED' was not upgraded to websocket
I/flutter ( 5598): ws channel closed
My question is, I want it to return server respond code when I entered correctly or when I entered wrong. I did the same thing in different languages ​​such as python, and it gives me feedback.
but here it comes only as null, I searched everywhere for the solution of this error for about 4 days, but I couldn't find it.waiting for you to help me
Best Regards

Related

How to check if the tcp socket is still connected in Flutter?

I have connected to my server as follows:
Socket socket = await Socket.connect('xxx', xxx)
But now I want to check if the socket is still connected. It would be even better if I have a listener that tells me when the connection is broken.
Thanks already!
Leonard
Listen to onDone in its stream
socket.stream.listen(
(dynamic message) {
debugPrint('message $message');
},
onDone: () {
debugPrint('socket closed');//if closed you will get it here
},
onError: (error) {
debugPrint('error $error');
},
);

Ignore http.post future exception

How can I ignore a future exception of a http.post call? In the following code I want to send a message to the server, but I don't care about the response:
http.post(Uri(host: '10.0.2.2', port: 8000, path: 'log-message', scheme: 'http'),
body: json.encode({
'message': 'Event occurred',
}));
If the server at that URL is not running, this exception is thrown:
SocketException (SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 10.0.2.2, port = 41874)
I can prevent this exception from being thrown by doing await on the above call and wrapping that around a try-catch, but I don't want to block. The following code still results in the above exception:
http.post(Uri(host: '10.0.2.2', port: 8000, path: 'log-message', scheme: 'http'),
body: json.encode({
'message': 'Event occurred',
}))
.catchError((_) => http.Response('Logging message failed', 404));
ignore() and onError() have the same result.
I want ignore whatever exception http.post could throw without having to do an await, which blocks the code.
If you just print the error that you catched, it should't block the app.
http.post('http:/10.0.2.2/log-message',
body: json.encode({
'message': 'Event occurred',
}));
.catchError((_) => print('Logging message failed'));
There is no way to catch a SocketException without waiting for the result of the http.post operation, because it occurs later than the request is sent. Whether you use async/await with try/catch or .then and .catchError is your choice, but the preferred way is async/await:
Future<Response> myFunction async {
try {
return http.post(...);
} on SocketException {
// handle the exception here as you like
}
}

Flutter: simple socket.io testing - Websocket pending

I have a super simple socket.io node server like below
// Socket!
io.on("connection", (socket) => {
console.log("a user connected");
socket.on("msg", (aaa) => {
console.log(aaa);
});
socket.on("fromServer", (_) => print(_));
console.log(socket.handshake.query)
});
And, here is my Flutter code to connect to the server
// Dart client
IO.Socket socket = IO.io(
'http://192.168.219.102:7199',
IO.OptionBuilder()
.setTransports(['polling'])
.disableAutoConnect()
.setQuery({"hee": 'asdf'})
.build());
socket.connect();
socket.onConnect((_) {
print(_);
});
On the network tab, I see two requests
101 HTTP 490ms
101 WS Pending
When I connect to the socket.io server from the other node.js server, I see the console.log of a user connected on the terminal. However, I see nothing from Flutter.
What can I do to receive the socket message on the server and connect the device.

Flutter: Catch firebase messaging connection

I implemented fiebase messaging in my flutter application. I am trying to catch it's connection error for example something like this:
6.26.0 - [Firebase/Messaging][I-FCM002025] Failed to connect to direct channel, error: Error Domain=com.google.fcm Code=4 "No internet available, cannot connect to FIRMessaging" UserInfo={NSLocalizedFailureReason=No internet available, cannot connect to FIRMessaging}
but there is no place to catch it. How can i catch firebase messaging connection?
final FirebaseMessaging _fcm = FirebaseMessaging();
_fcm.getToken().then((value) {
_token = value;
print("Message token is: $_token");
}, onError: (err) {
print("getToken onError is: $err");
}).catchError((onError) {
print("getToken catchError is: $onError");
});

What is the proper way of detecting network errors in stream downloads using Axios in Nest.js?

I'm working with the HttpService module from Nest.js to make the HTTP calls. I'm able to download an image from https://unsplash.com; when there is no network interruptions the code is working as expected.
This is the code I have for making the download call and start writing into the desired file
const urlDownload = 'https://unsplash.com/photos/xiie4XeSzTU/download?force=true';
let response = await this.httpService.get(urlDownload, {
responseType: 'stream'
}).toPromise();
response.data.pipe(writer);
And this is the code where I'm trying to handle the possible events of the writer and returning a response
let downloadFile = path.resolve(__dirname,'../../files/landscape.jpg');
let writer = fs.createWriteStream(downloadFile);
return new Promise((resolve, reject) => {
writer.on('finish', ()=>{
resolve('Image downloaded');
});
writer.on('error', ()=>{
reject('Image downloaded failed');
});
});
I'm deliberately turning off the wifi during the download to try the server response with Image downloaded failed (what I have in the writer error handler), but instead I'm getting an 500 statusCode, internal server error. When I go to the Nest console to whatch the error it appears
[Nest] 11220 - 2020-05-22 18:16:45 [ExceptionsHandler] getaddrinfo ENOTFOUND unsplash.com +439536ms
Error: getaddrinfo ENOTFOUND unsplash.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:64:26)
How can I solve this and catch correcty the network error from Nest to return a friendly message?
I could solve it. I let it here with the hope of helping somebody in the future.
It is not firing the error handler function because that handler is attached to the writter, and there is not writting error, it just stops writing because the cut of the connection but that is not an error.
I re-writed the response variable to stop being a promise and better I started treating it like an observer.
let response = this.httpService.get(urlDownload, {
responseType: 'stream',
});
And then it is the response in previus Promise format
return new Promise((resolve, reject) => {
writer.on('error', () => {
resolve('error due to, possibly, an unexisting file path');
})
response.subscribe({
next(response) { response.data.pipe(writer) },
error(err) {
console.error('More details: ' + err);
resolve('Error in the download :/')
},
complete() { resolve('Completed'); }
})
});
I'm not using the reject function of the promise but it is perfectly doable