2023-07-26 18:07:30 +00:00
|
|
|
import 'dart:io';
|
|
|
|
|
|
|
|
class SocketWrapper {
|
|
|
|
late Socket _socket;
|
|
|
|
final String serverIP;
|
|
|
|
final int serverPort;
|
|
|
|
|
2023-07-27 17:33:39 +00:00
|
|
|
late Stream<List<int>>
|
|
|
|
_receiveStream; // create a field for the broadcast stream
|
2023-07-26 18:07:30 +00:00
|
|
|
|
|
|
|
SocketWrapper(this.serverIP, this.serverPort);
|
|
|
|
Socket get socket => _socket;
|
|
|
|
|
2023-07-27 17:33:39 +00:00
|
|
|
Stream<List<int>> get receiveStream =>
|
|
|
|
_receiveStream; // expose the stream with a getter
|
2023-07-26 18:07:30 +00:00
|
|
|
|
|
|
|
Future<void> connect() async {
|
|
|
|
_socket = await Socket.connect(serverIP, serverPort);
|
2023-07-27 17:33:39 +00:00
|
|
|
_receiveStream =
|
|
|
|
_socket.asBroadcastStream(); // initialize the broadcast stream
|
2023-07-26 18:07:30 +00:00
|
|
|
_socket.done.then((_) {
|
|
|
|
print('......Socket has been closed');
|
|
|
|
});
|
|
|
|
_socket.handleError((error) {
|
|
|
|
print('Socket error: $error');
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
void status() {
|
|
|
|
if (_socket != null) {
|
2023-07-27 17:33:39 +00:00
|
|
|
print(
|
|
|
|
"Socket connected to ${_socket.remoteAddress.address}:${_socket.remotePort}");
|
2023-07-26 18:07:30 +00:00
|
|
|
} else {
|
|
|
|
print("Socket is not connected");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> send(List<int> data) async {
|
|
|
|
if (_socket != null) {
|
|
|
|
_socket.add(data);
|
|
|
|
await _socket.flush();
|
|
|
|
} else {
|
|
|
|
// handle error
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void close() {
|
|
|
|
_socket.close();
|
|
|
|
}
|
|
|
|
}
|