init method
Implementation
String init(String url, WebSocketEventCallback callback, {String? protocols}) {
var id = (_clientId++).toString();
WebSocket.connect(url, protocols: protocols != null ? [protocols] : null).then((webSocket) {
IOWebSocketChannel client = IOWebSocketChannel(webSocket);
_WebSocketState? state = _stateMap[id];
if (state != null && state.status == _ConnectionState.closed) {
dynamic data = state.data;
webSocket.close(data[0], data[1]);
CloseEvent event = CloseEvent(data[0] ?? 0, data[1] ?? '', true);
callback(id, event);
_stateMap.remove(id);
return;
}
_clientMap[id] = client;
// Listen all event
_listen(id, callback);
if (_hasListener(id, EVENT_OPEN)) {
Event event = Event(EVENT_OPEN);
callback(id, event);
}
}).catchError((e, stack) {
// print connection error internally and trigger error event.
print(e);
Event event = Event(EVENT_ERROR);
callback(id, event);
});
return id;
}