connectLocalSocket function
Connects to a media socket with the specified options.
Returns a ResponseLocalConnection containing the socket and connection data.
Throws an exception if inputs are invalid or if connection fails.
Example usage:
final options = ConnectLocalSocketOptions(
link: "http://localhost:3000",
);
try {
final response = await connectLocalSocket(options);
print("Connected to local socket with ID: ${response.data.socketId}");
} catch (error) {
print("Failed to connect to local socket: $error");
}
Connects to a local media socket with the specified options.
Returns a ResponseLocalConnection containing the socket and connection data.
Supports optional authentication parameters for backend handshake.
Implementation
/// Connects to a local media socket with the specified options.
/// Returns a `ResponseLocalConnection` containing the socket and connection data.
/// Supports optional authentication parameters for backend handshake.
Future<ResponseLocalConnection> connectLocalSocket(
ConnectLocalSocketOptions options) async {
if (options.link.isEmpty) throw Exception('Socket link required.');
// Build query parameters for handshake authentication
final Map<String, dynamic> query = {};
if (options.appKey != null && options.appKey!.isNotEmpty) {
query['appKey'] = options.appKey;
}
if (options.apiUserName != null && options.apiUserName!.isNotEmpty) {
query['apiUserName'] = options.apiUserName;
}
if (options.apiKey != null && options.apiKey!.isNotEmpty) {
query['apiKey'] = options.apiKey;
}
final socket = io.io('${options.link}/media', <String, dynamic>{
'transports': ['websocket'],
if (query.isNotEmpty) 'query': query,
});
// final socket = io.io('${options.link}/media', {
// 'transports': ['websocket'],
// 'query': {},
// });
final completer = Completer<ResponseLocalConnection>();
// Handle connection success
socket.on('connection-success', (data) {
if (!completer.isCompleted) {
final connectionData =
ResponseLocalConnectionData.fromMap(Map<String, dynamic>.from(data));
completer.complete(
ResponseLocalConnection(socket: socket, data: connectionData));
}
});
// Handle connection error
socket.onConnectError((error) {
if (!completer.isCompleted) {
completer.completeError(
Exception('Error connecting to local media socket: $error'));
}
});
return completer.future;
}