web_socket.dart 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import 'package:web_socket_channel/web_socket_channel.dart';
  2. import 'package:web_socket_channel/status.dart' as status;
  3. import 'package:flutter/material.dart';
  4. class WebSocketScreen extends StatelessWidget {
  5. const WebSocketScreen({Key? key}) : super(key: key);
  6. @override
  7. Widget build(BuildContext context) {
  8. return Scaffold(
  9. appBar: AppBar(
  10. title: const Text('WebSocket Example'),
  11. leading: IconButton(
  12. icon: const Icon(Icons.arrow_back),
  13. onPressed: () => Navigator.pop(context),
  14. ),
  15. ),
  16. body: Center(
  17. child: Column(
  18. children: [
  19. ElevatedButton(
  20. onPressed: () async {
  21. connectButtonClicked();
  22. },
  23. child: const Text('Connect to WebSocket'),
  24. ),
  25. ElevatedButton(
  26. onPressed: () async {
  27. sendButtonClicked();
  28. },
  29. child: const Text('Send Message'),
  30. ),
  31. ],
  32. ),
  33. ),
  34. );
  35. }
  36. }
  37. void connectButtonClicked() async {
  38. final wsUrl = Uri.parse('ws://47.76.151.238:82/ws');
  39. final channel = WebSocketChannel.connect(wsUrl);
  40. await channel.ready;
  41. channel.stream.listen((message) {
  42. print('Received: $message');
  43. });
  44. await Future.delayed(Duration(seconds: 2));
  45. channel.sink.add('Hello World!');
  46. print('Sent: Hello World!');
  47. await Future.delayed(Duration(seconds: 2));
  48. channel.sink.close(status.goingAway);
  49. print('Connection closed');
  50. }
  51. void sendButtonClicked() async {}