Created
June 25, 2020 19:49
-
-
Save agilob/f8684bbf6a6fecb9d66db08e0bb0f1d9 to your computer and use it in GitHub Desktop.
Example use of dart.io websocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WebSocket _wss; // class level field, so you can use it in methods | |
//method level | |
await WebSocket.connect(uri).timeout((Duration(seconds: 5))).then( | |
(WebSocket ws) { | |
_wss = ws; | |
if (_wss?.readyState == WebSocket.open) { | |
// you can tell server who you are here, right after connecting | |
_wss.listen( | |
(data) { | |
// you get data from server here | |
final msg = YourClass.fromJson(json.decode(data)); | |
// process message here | |
}, | |
onDone: () => { | |
log.fine(' WS closed'), | |
}, | |
onError: (err) => { | |
log.info('Error -- ${err.toString()}'), | |
}, | |
cancelOnError: true, | |
); | |
} else { | |
log.info('Connection Failed'); | |
// in case, if server is not running now | |
} | |
}, | |
onError: (err) => { | |
log.severe('${err.toString()}'), | |
}, | |
); | |
// send to websocket: | |
if (_wss?.readyState == WebSocket.open) { | |
_wss.add( | |
json.encode( | |
// your json object here | |
), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment