The shelf_web_socket package provides a Shelf handler for establishing WebSocket connections. You can use the webSocketHandler function to create a Handler that triggers an onConnection callback whenever a new connection is established.
The callback receives two arguments:
- A
WebSocketChannel object representing the connection. - An
HttpRequest object representing the initial handshake request.
You can interact with the connection using the stream property to listen for incoming messages and the sink property to send messages back to the client.
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
void main() {
// Create a handler that echoes received messages
var handler = webSocketHandler((webSocket, _) {
webSocket.stream.listen((message) {
webSocket.sink.add('echo $message');
});
});
// Serve the handler using shelf_io
shelf_io.serve(handler, 'localhost', 8080).then((server) {
print('Serving at ws://${server.address.host}:${server.port}');
});
}