Skip to content

Instantly share code, notes, and snippets.

@mmaitlen
Last active July 11, 2024 00:23
Show Gist options
  • Select an option

  • Save mmaitlen/19d9d0c91db29a55bc8cf883da03a511 to your computer and use it in GitHub Desktop.

Select an option

Save mmaitlen/19d9d0c91db29a55bc8cf883da03a511 to your computer and use it in GitHub Desktop.
Flutter/Dart Websocket server
/// A simple websocket server Flutter app that can ping a connected client
/// thanks to Simon Lightfoot @devangelslondon and Craig Labenz @craig_labenz
/// #boringshow https://youtu.be/AaQzV1LTmo0?si=2xjcfH0FA5tt4nyW
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart' as router;
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
void main() {
runApp(const MainApp());
}
final _router = router.Router()..get('/ws', webSocketHandler(_handleWebSocket));
WebSocketChannel? wsc;
Future<void> _startServer() async {
final ip = InternetAddress.anyIPv4;
final handler = const Pipeline().addMiddleware(logRequests()).addHandler(_router);
final port = int.parse(Platform.environment['PORT'] ?? '8081');
final server = await serve(handler, ip, port);
debugPrint('Server listening on port ${server.port}');
}
void _handleWebSocket(WebSocketChannel webSocket) {
debugPrint("client connected");
webSocket.stream.listen((message) {
debugPrint("echo to client $message");
webSocket.sink.add("echo $message");
}, onDone: () {
debugPrint('client connection closed');
});
wsc = webSocket;
}
class MainApp extends StatefulWidget {
const MainApp({super.key});
@override
State<MainApp> createState() => _MainAppState();
}
class _MainAppState extends State<MainApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.white,
body: Center(
child: Column(
children: [
const Text('--- SERVER ---'),
const SizedBox(height: 8),
const ElevatedButton(
onPressed: _startServer,
child: Text("start server"),
),
const SizedBox(height: 8),
ElevatedButton(
onPressed: () {
wsc?.sink.add('ping from server');
},
child: const Text("ping client"))
],
),
),
),
);
}
}
name: websocket_server
description: "Websocket server"
publish_to: "none"
version: 0.1.0
environment:
sdk: ">=3.2.6 <4.0.0"
dependencies:
flutter:
sdk: flutter
shelf: ^1.4.1
shelf_router: ^1.1.4
shelf_web_socket: ^2.0.0
web_socket_channel: ^2.4.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
uses-material-design: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment