requestHandel method
Handles an incoming WebSocket request and establishes a WebSocket connection.
The rq
parameter is the WebRequest that initiated the WebSocket upgrade.
The optional userId
parameter associates the WebSocket connection with a specific user.
Implementation
Future<WebRequest> requestHandel(WebRequest rq, {String? userId}) async {
var socket = await WebSocketTransformer.upgrade(rq.httpRequest);
final id = rq.headers['sec-websocket-key']!.first;
session.add(
id,
SocketClient(
id: id,
socket: socket,
rq: rq,
manager: this,
),
userID: userId,
);
if (session.getClient(id) != null) {
event?.onConnect?.call(session.getClient(id)!);
}
socket.listen(
(data) {
var res = <String, dynamic>{};
try {
res = WaJson.jsonDecoder(data);
} catch (e) {
res = {'path': 'error', 'data': data};
}
if (routes.containsKey(res['path'] ?? '')) {
routes[res['path']]?.onMessage!(session.getClient(id)!, res);
} else if (event?.onMessage != null) {
event?.onMessage!(session.getClient(id)!, res);
}
},
onDone: () async {
await event?.onDisconnect?.call(session.getClient(id)!);
session.remove(id);
},
onError: (data) async {
var res = <String, dynamic>{};
try {
res = jsonDecode(data);
} catch (e) {
res = {'path': 'error', 'data': data};
}
event?.onMessage!(session.getClient(id)!, res);
event?.onError?.call(session.getClient(id)!, res);
await event?.onDisconnect?.call(session.getClient(id)!);
session.remove(id);
},
cancelOnError: true,
);
return rq;
}