Created
February 5, 2022 11:10
-
-
Save felixblaschke/b663c232e187131e4cffe745b92a6cc9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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