The Dart SDK is currently in experimental status. If you would like to provide feedback, please reach out to us with your suggestions and comments on our Discord.
Dart - websocket.send()
Send a message to a connected websocket client.
import 'package:nitric_sdk/nitric.dart';
final socket = Nitric.websocket("socket");
await socket.send(connectionId, message);
Parameters
- Name
connectionId
- Required
- Required
- Type
- String
- Description
The ID of the connection which should receive the message.
- Name
message
- Required
- Required
- Type
- Map<String, dynamic>
- Description
The message that should be sent to the connection.
Examples
Broadcasting a message to all connections.
Do not send messages to a connection during it's connect
callback, if you
need to acknowledge connection, do so by using a topic
import 'package:nitric_sdk/nitric.dart';
final socket = Nitric.websocket("socket");
final connections = Nitric.kv("connections").allow([
KeyValueStorePermission.get,
KeyValueStorePermission.set,
KeyValueStorePermission.delete,
]);
socket.onConnect((ctx) async {
await connections.set(ctx.req.connectionId, {
// add metadata
"creation_time": DateTime.now(),
});
return ctx;
});
socket.onDisconnect((ctx) async {
await connections.delete(ctx.req.connectionId);
});
// broadcast message to all clients (including the sender)
socket.onMessage((ctx) async {
final conns = await connections.keys();
await Future.wait(await conns.map((conn) async {
// Send a message to a connection
return socket.send(conn, ctx.req.message);
}).toList());
return ctx;
});