Skip to content

Instantly share code, notes, and snippets.

@felixblaschke
Created February 5, 2022 11:10
Show Gist options
  • Save felixblaschke/b663c232e187131e4cffe745b92a6cc9 to your computer and use it in GitHub Desktop.
Save felixblaschke/b663c232e187131e4cffe745b92a6cc9 to your computer and use it in GitHub Desktop.
import 'dart:io';
import 'package:shelf_plus/shelf_plus.dart';
void main() => shelfRun(init);
Handler init() {
var app = Router().plus;
// Track connected clients
var users = <WebSocketSession>[];
// Web socket route
app.get(
'/ws',
() => WebSocketSession(
onOpen: (ws) {
// Join chat
users.add(ws);
users
.where((user) => user != ws)
.forEach((user) => user.send('A new user joined the chat.'));
},
onClose: (ws) {
// Leave chat
users.remove(ws);
for (var user in users) {
user.send('A user has left.');
}
},
onMessage: (ws, dynamic data) {
// Deliver messages to all users
for (var user in users) {
user.send(data);
}
},
),
);
return app;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment