How to show Unhandled Exception message to View FLUTTER - flutter

How to show this message to view? so that the user knows that the connection cannot connect to the server
this my socket connection code :
Socket.connect(pIp, port, timeout: const Duration(seconds: 5))
.then((socket) {
_channel = socket;
_isOn = true;
if (pWithdata.isNotEmpty) {
if (_channel != null) {
send(pWithdata);
// submitMessage("LOGIN#xXYjY`#Uf]bXcMM#FFHE#V30#V901");
}
}
socket.listen(
(onData) {
_isOn = true;
_listeners.forEach((Function callback) {
// callback(onData);
callback(String.fromCharCodes(onData).trim());
});
},
onDone: onDone,
onError: onError,
);
});

Related

Flutter How to check connection TCP IP

I want to perform an operation, but before that I want to check the connection status to the server whether it is still connected or not. If it is connected then perform the operation, if not then reconnect.
here is my code on button on pressed
Future<void> masuk() async {
if (_socketConnection == null) {
setState(() {
connect();
});
} else if (_subscription == null) {
setState(() {
connect();
});
} else {
_getId().then((id) {
setState(() {
deviceId = id;
print("Sambungan Masih terhubung");
send();
});
});
}
}
and here is code for connection
Future<void> connect() async {
var server = "10.0.2.2";
int port = 8000;
if (server.isNotEmpty) {
SocketClient socketClient = SocketClient(server, port);
_subscription = socketClient.connect().doOnCancel(() {
setState(() {
_subscription = null;
_socketConnection = null;
});
}).listen((connection) async {
print("listen:$connection");
setState(() {
_socketConnection = connection;
});
}, onError: (error) {
_result = "Connect Error:$error";
_subscription?.cancel();
setState(() {
_subscription = null;
_socketConnection = null;
});
}, cancelOnError: true);
}
setState(() {});
}
I have to restart the application first if I want to reconnect if the condition is "The server is off or restarted"

how to detect connection in flutter

so i have this function which detect if there is connection or not . if yes the var activeConnection is true else false . So if the connection is working i'm going to call a method sendEmail() which work with the plugin mailer . My problem is when i activated the WIFI it can send the email then if i turn it off an exception is shown
E/flutter ( 5347): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)]
Unhandled Exception: SocketException: Failed host lookup:
'smtp.gmail.com' (OS Error: No address associated with hostname, errno
= 7)
in this case activeConnection is true but when it try to send the email it can't find the connection . if i turn off the wifi and wait for a moment before i send the email it can detect that there is no wifi so i tried to add a sleep function before it check the connection but i'm facing the same problem .
this is the code :
Future checkUserConnection() async {
try {
//sleep(const Duration(seconds: 10));
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
setState(() {
activeConnection = true;
print(activeConnection);
});
}
} on SocketException catch (_) {
setState(() {
activeConnection = false;
print(activeConnection);
});
}
//print(activeConnection);
}
and this is where i call my function
onTap: () {
checkUserConnection();
print(activeConnection);
if (activeConnection) {
sendEmail();
ScaffoldMessenger.of(context).showSnackBar(showSnackBar(
false, "email sended ", Icons.error_outline));
} else {
ScaffoldMessenger.of(context).showSnackBar(showSnackBar(
true,
"check your internet connection !!!",
Icons.error_outline));
}
print("hello");
},
You have to make async function like this:
Future<bool> checkUserConnection() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return true;
}
} on SocketException catch (_) {
return false;
}
}
After that onTap() you have to code like this:
onTap: () {
checkUserConnection().then((activeConnection){
if (activeConnection) {
sendEmail();
ScaffoldMessenger.of(context).showSnackBar(showSnackBar(
false, "email sended ", Icons.error_outline));
} else {
ScaffoldMessenger.of(context).showSnackBar(showSnackBar(
true, "check your internet connection !!!",
Icons.error_outline));
}
});
}

Client only listens to server when sends a message

I'm implementing socket.
Two clients connect to the server with no problem, when client1 sends a message to the server, the server publishes it to every other client (which in this case is client2). but client2 won't get the message unless it sends a message. It seems the listener of the client doesn't work. Obviously, I want client2 to get the message from client1 instantly.
here is my sever code:
import 'dart:io';
import 'dart:typed_data';
void main() async {
// bind the socket server to an address and port
MySocket mySocket = MySocket();
await mySocket.init();
}
class MySocket {
ServerSocket? server;
List<Socket> clients = [];
//initialize the socket
init() async {
server = await ServerSocket.bind("192.168.0.112", 4000);
// listen for client connections to the server
server!.listen((client) {
handleConnection(client);
addClient(client);
});
}
void handleConnection(Socket client) async {
print('Connection from'
' ${client.remoteAddress.address}:${client.remotePort}');
// listen for events from the client
client.listen(
// handle data from the client
(Uint8List data) async {
await Future.delayed(Duration(seconds: 1));
final message = String.fromCharCodes(data);
print(message);
publish(message, client);
},
// handle errors
onError: (error) {
print(error);
client.close();
},
// handle the client closing the connection
onDone: () {
print('Client left');
client.close();
},
);
}
void addClient(Socket client) {
//if client doesn't already exist add it to the list of clients
if (!clients.any((element) =>
'${client.remoteAddress.address}:${client.remotePort}' ==
'${element.remoteAddress.address}:${element.remotePort}')) {
clients.add(client);
}
}
void publish(String message, Socket client) {
//write the message to every client except the author of it
clients.forEach((element) async {
if ('${client.remoteAddress.address}:${client.remotePort}' !=
'${element.remoteAddress.address}:${element.remotePort}') {
element.write(message);
}
});
}
}
here is my client-side code:
import 'dart:io';
import 'dart:typed_data';
void main() async {
//gets the username
String name = '';
while (name.isEmpty) {
print('Enter your name: ');
name = stdin.readLineSync() ?? '';
}
// connect to the socket server
final socket = await Socket.connect("192.168.0.112", 4000);
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);
print('$serverResponse');
},
// handle errors
onError: (error) {
print(error);
socket.destroy();
},
// handle server ending connection
onDone: () {
print('Left server.');
socket.destroy();
},
);
// sending messages to the server
String message = "";
while (message != "exit") {
message = stdin.readLineSync() ?? '';
await sendMessage(socket, name, message);
}
socket.close();
}
Future<void> sendMessage(Socket socket, String name, String message) async {
socket.write('$name: $message');
await Future.delayed(Duration(seconds: 2));
}
Thank you in advance.
The issue is because stdin.readLineSync() in your client blocks the current thread. You can get around this by spawning an isolate to handle that portion of the code, so that it does not block the socket.listen from printing out the responses from the server.
See updated client code below:
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
void main() async {
//gets the username
String name = '';
while (name.isEmpty) {
print('Enter your name: ');
name = stdin.readLineSync() ?? '';
}
// connect to the socket server
final socket = await Socket.connect("192.168.0.112", 4000);
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);
print('$serverResponse');
},
// handle errors
onError: (dynamic error) {
print(error);
socket.destroy();
},
// handle server ending connection
onDone: () {
print('Left server.');
socket.destroy();
},
);
final receive = ReceivePort();
final isolate = await Isolate.spawn(readMessages, receive.sendPort);
await for (final message in receive) {
if (message == 'exit') break;
await sendMessage(socket, name, message as String);
}
socket.close();
}
void readMessages(SendPort port) {
String message = '';
while (message != 'exit') {
message = stdin.readLineSync() ?? '';
port.send(message);
}
Isolate.exit(port);
}
Future<void> sendMessage(Socket socket, String name, String message) async {
socket.write('$name: $message');
await Future<void>.delayed(Duration(seconds: 2));
}

Flutter websocket closes after some time

const CIM_HOST = "";
const CIM_PORT = '34567';
const CIM_URI = "wss://" + CIM_HOST;
_channel = WebSocketChannel.connect(
Uri.parse(CIM_URI),
);
_channel.sink.add(protobuff);
_channel.stream.listen(
//on message
(event) {
var list = event;
var bytes = Uint8List.fromList(list);
var type = bytes[0];
var body = bytes.sublist(1, bytes.length);
final message = js.context.callMethod('type2deserializeBinary', [body]);
print(message.toString());
if (message == null) {
_channel.sink.close();
timer.cancel();
// Navigator.pushReplacement<void, void>(
// context,
// MaterialPageRoute<void>(
// builder: (BuildContext context) => LoginScreen(),
// ),
// );
} else {
List<String> result = message.toString().split(',');
if (currentid == result[3]) {
int id = int.parse(result[3]);
setMessage("reply", result[2], id, 'text');
// print(result);
}
}
},
//on close
onDone: () {
debugPrint('ws channel closed');
//reconnect to socket server
},
//on error
onError: (error) {
debugPrint('ws error $error');
},
);`enter code here`
i have this code to connect to the socket and to list the messages but the connection gets closed after some time.i tried to call the connection method again inside the ondone but that causes the list values to duplicate so can anyone tell me how to maintain the connection.

Server Socket is not working in my Flutter App and I am not able to listen any updates after connection

Flutter Server Sockets
I used Server Socket for my flutter app. But not able to listen or get any update . I even I don't know if its connected or not. Here is my code black for all socket work and i have called this in initState
#override
void initState() {
startServer();
super.initState();
}
late ServerSocket serverSocket;
late Socket clientSocket;
void startServer() async {
print(serverSocket);
serverSocket =
await ServerSocket.bind(InternetAddress.anyIPv4, 6000, shared: true);
print(serverSocket);
serverSocket.listen(handleClient);
}
void handleClient(Socket client) {
clientSocket = client;
clientSocket.listen(
(onData) {
print("Listening");
print(String.fromCharCodes(onData).trim());
setState(() {});
},
onError: (e) {
disconnectClient();
},
onDone: () {
disconnectClient();
},
);
}
void stopServer() {
disconnectClient();
serverSocket.close();
setState(() {
// serverSocket = null;
});
}
void disconnectClient() {
clientSocket.close();
clientSocket.destroy();
setState(() {
//clientSocket = null;
});
}