How to realize the continuous output of data from the server to the client. For example, after receiving the start command from the client, the server keeps outputting the current time to the client until the server receives the quit command.
Questions:
- Why can't the server receive the
quitcommand - Why only the first client can receive the continuous output message from the server
My code in Dart is
Server:
import 'dart:io';
main() async {
var running = true;
var q = 'quit';
var p;
final port = 8080;
var webSocketTransformer = WebSocketTransformer();
HttpServer server = await HttpServer.bind(InternetAddress.anyIPv6, port);
server.transform(webSocketTransformer).listen((WebSocket webSocket) {
print('WebSocket opened.');
webSocket.listen((_) {
q = _;
print(_);
}, onError: (err) {
running = false;
print(err);
}, onDone: () {
running = false;
print('WebSocket closed.');
});
while (running && p != q) {
sleep(Duration(seconds: 1));
webSocket.add(DateTime.now().toString());
}
});
print('Listening..');
}
Client:
import 'dart:io';
import 'package:web_socket_channel/io.dart';
void main(List<String> arguments) {
final url = 'ws://localhost:8080';
final channel = IOWebSocketChannel.connect(url);
channel.sink.add('start');
channel.stream.listen((msg) {
print(msg);
});
sleep(Duration(seconds: 30));
channel.sink.add('quit');
}