I made a simple server app with Dart that receives and returns messages. It works great except when I stop the program the server keeps running in the background and I have to go to the cmd to kill the task before running the program again.
Why does the server not terminate when the program is stopped, and how do I fix that?
import 'dart:io' show HttpServer, HttpRequest, WebSocket, WebSocketTransformer;
void main() {
var sockets = <WebSocket>[];
var i = 0;
HttpServer.bind('localhost', 8080).then((HttpServer server) {
print('[+]WebSocket listening at -- ws://localhost:8080/');
server.listen((HttpRequest request) {
WebSocketTransformer.upgrade(request).then((WebSocket ws) {
sockets.add(ws);
ws.listen(
(data) {
print(data);
for(var socket in sockets) {
socket.add('a msg back from the server: $i');
}
i++;
},
onDone: () => print('[+]Done :)'),
onError: (err) => print('[!]Error -- ${err.toString()}'),
cancelOnError: true,
);
}, onError: (err) => print('[!]Error -- ${err.toString()}'));
}, onError: (err) => print('[!]Error -- ${err.toString()}'));
}, onError: (err) => print('[!]Error -- ${err.toString()}'));
}
Thanks in advance for the help.