Hi Matt,
There are two problems here; the unhandled exception and the fact that you actually get the exception. Let's start with the former.
The "WebSocketException: Invalid WebSocket upgrade request" exception is throws by the dart:io, when it's unable to upgrade HttpRequest to a WebSocket. There are two ways to do this with the API in dart:io.
With futures:
server.listen((request) {
WebSocketTransformer.upgrade(request).then((webSocket) {
// Success, upgraded
})
.catchError((error, stackTrace) {
// Failed to upgrade (the above exception would be caught here).
});
});
and with streams:
server
.transform(new WebSocketTransformer())
.listen((webSocket) {
// Success, a request was upgraded
}, onError: (error, stackTrace) {
// Failed to upgrade (the above exception would be caught here).
// Can be called multiple times for streams.
});
});
Depending on which API you use, you can use the above for inspiration on how to catch this error.
Now, the other problem, that you actually see this error. I'm not sure how you did this, but if a browser tries to connect to your server as a regular GET request and you try to upgrade the request, it will fail like above, as the right headers are not set. Be sure to only upgrade the requests meant for websocket communication. A common pattern is to use either a different port or a unique path, e.g.
ws://myhost/ws
And then only attempt to upgrade the requests where the path is equal to '/ws'.
I hope this can help you a bit further.
Cheers,
- Anders