-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnectionCtrl.dart
53 lines (41 loc) · 1.12 KB
/
connectionCtrl.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import './room.dart';
import 'command/command.dart';
import 'protocol/protocol.dart';
class ConnectionCtrl {
final _id;
get id => _id;
Socket _socket;
ConnectionCtrl(this._id, this._socket, Room room) {
_socket.listen(
(data) => _readMessage(data, room),
onDone: () => {_leave(room)},
);
}
void _leave(Room room) {
print("[ConnCtrl($_id) Leave]");
room.removeListener(_id);
final json = jsonEncode({
"leaveId": _id,
"member": room.getIds().add(1),
});
room.broadcast(json);
}
void _readMessage(Uint8List data, Room room) {
final msg = String.fromCharCodes(Protocol.Read(data));
final Command cmd = Command.fromJson(jsonDecode(msg));
print("[ConnCtrl($_id) Read]: $msg");
final json = jsonEncode({
"sender": _id,
"message": cmd.message,
});
if (cmd.isBroadcast())
room.broadcast(json);
else
room.unicast(cmd.target, json);
}
void _eventListener(String msg) => Protocol.Write(_socket, msg.codeUnits);
get eventListener => _eventListener;
}