connectToTcpServer method
Implementation
Future<void> connectToTcpServer(String host, int port) async {
try {
_tcpSocket = await Socket.connect(host, port);
_isConnected = true;
print('Connected to server at ${_tcpSocket?.remoteAddress}:${_tcpSocket?.remotePort}');
_tcpSocket?.listen(
(Uint8List data) {
final message = String.fromCharCodes(data);
print('Received: $message');
},
onError: (error) {
print('Error: $error');
_isConnected = false;
_tcpSocket?.close();
},
onDone: () {
print('Server disconnected');
_isConnected = false;
_tcpSocket?.close();
},
);
} catch (e) {
print('Error connecting to TCP server: $e');
}
}