Skip to content

Commit

Permalink
bug fix on websocket room id
Browse files Browse the repository at this point in the history
  • Loading branch information
necessarylion committed Dec 16, 2023
1 parent 9145610 commit ee45756
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 65 deletions.
2 changes: 0 additions & 2 deletions packages/dox-websocket/lib/src/utils/constant.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,3 @@ const String WEB_SOCKET_MESSAGE_KEY = 'message';
const String WEB_SOCKET_SENDER_KEY = 'sender';

const String WEB_SOCKET_ROOM_KEY = 'room';

const String WEB_SOCKET_DEFAULT_ROOM_NAME = '__default';
22 changes: 13 additions & 9 deletions packages/dox-websocket/lib/src/websocket_emit_event.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ class WebsocketEmitEvent {
final String event;
final List<dynamic> exclude;

const WebsocketEmitEvent(
this.senderId, this.roomId, this.message, this.event, this.exclude);
const WebsocketEmitEvent({
required this.senderId,
required this.roomId,
required this.message,
required this.event,
required this.exclude,
});

@override
toString() {
Expand All @@ -25,11 +30,11 @@ class WebsocketEmitEvent {
static fromString(String json) {
Map<String, dynamic> jsond = JSON.parse(json);
return WebsocketEmitEvent(
jsond['senderId'],
jsond['roomId'],
jsond['message'],
jsond['event'],
jsond['exclude'],
senderId: jsond['senderId'],
roomId: jsond['roomId'],
message: jsond['message'],
event: jsond['event'],
exclude: jsond['exclude'],
);
}

Expand All @@ -38,8 +43,7 @@ class WebsocketEmitEvent {
WEB_SOCKET_EVENT_KEY: event,
WEB_SOCKET_MESSAGE_KEY: message,
WEB_SOCKET_SENDER_KEY: senderId,
WEB_SOCKET_ROOM_KEY:
roomId == WEB_SOCKET_DEFAULT_ROOM_NAME ? null : roomId,
WEB_SOCKET_ROOM_KEY: roomId,
});
}
}
27 changes: 18 additions & 9 deletions packages/dox-websocket/lib/src/websocket_emitter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ class WebsocketEmitter {
/// ```
/// emitter.room('ABC');
/// ```
WebsocketEmitter room(dynamic id) {
_roomId = id;
WebsocketEmitter room(dynamic room) {
_roomId = room;
return this;
}

Expand All @@ -35,8 +35,13 @@ class WebsocketEmitter {
void emitToSender(String event, dynamic message) {
WebsocketInfo? info = _storage.getWebSocketInfo(sender);
if (info != null) {
WebsocketEmitEvent emitEvent =
WebsocketEmitEvent(sender, _roomId, message, event, []);
WebsocketEmitEvent emitEvent = WebsocketEmitEvent(
senderId: sender,
roomId: _roomId,
message: message,
event: event,
exclude: [],
);

/// we do not need to send via adaptor
/// since sender will be always on the same isolate
Expand All @@ -45,22 +50,27 @@ class WebsocketEmitter {
}
}

/// set message except the sender
/// sent message except the sender
/// ```
/// emitter.emitExceptSender('event', message);
/// ```
void emitExceptSender(String event, dynamic message) {
emit(event, message, exclude: <String>[sender]);
}

/// set message to everyone in the room
/// sent message to everyone in the room
/// ```
/// emitter.emit('event', message);
/// ```
void emit(String event, dynamic message,
{List<String> exclude = const <String>[]}) {
WebsocketEmitEvent emitEvent =
WebsocketEmitEvent(sender, _roomId, message, event, exclude);
WebsocketEmitEvent emitEvent = WebsocketEmitEvent(
senderId: sender,
roomId: _roomId,
message: message,
event: event,
exclude: exclude,
);

WebsocketAdapterInterface? adapter = WebsocketServer().getAdapter();

Expand All @@ -70,7 +80,6 @@ class WebsocketEmitter {
emitEventToSockets(emitEvent);
return;
}

adapter.emit(emitEvent);
}

Expand Down
10 changes: 6 additions & 4 deletions packages/dox-websocket/lib/src/websocket_event.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,17 @@ class WebsocketEventHandler implements WebsocketEvent {
/// socketId is just `uuid` generated by us
String socketId = _createSocketId();

/// set default room id as route identifier
String defaultRoomId = 'room:${req.getRouteIdentifier()}';

/// prepare emitter to pass to controller
WebsocketEmitter emitter =
WebsocketEmitter(socketId, WEB_SOCKET_DEFAULT_ROOM_NAME);
WebsocketEmitter emitter = WebsocketEmitter(socketId, defaultRoomId);

/// add to active ws connection storage to reuse later
_storage.addWebSocketInfo(socketId, ws);

/// add socket id to the room default room is the route eg. /ws
_storage.addWebSocketIdToRoom(socketId, WEB_SOCKET_DEFAULT_ROOM_NAME);
_storage.addWebSocketIdToRoom(socketId, defaultRoomId);

/// send connected event to client
emitter.emitToSender('connected', <String, String>{'id': socketId});
Expand All @@ -63,7 +65,7 @@ class WebsocketEventHandler implements WebsocketEvent {
/// if event name is WEB_SOCKET_JOIN_ROOM_EVENT_NAME,
/// join to the room and message is room name
if (eventName == WEB_SOCKET_JOIN_ROOM_EVENT_NAME) {
String room = message;
String room = defaultRoomId + message;
_storage.addWebSocketIdToRoom(socketId, room);
return;
}
Expand Down
12 changes: 7 additions & 5 deletions packages/dox-websocket/test/config/app_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import 'router.dart';

class ResponseHandler extends ResponseHandlerInterface {
@override
void handle(DoxResponse res) {}
DoxResponse handle(DoxResponse res) {
return res;
}
}

AppConfig appConfig = AppConfig(
Expand All @@ -16,13 +18,13 @@ AppConfig appConfig = AppConfig(
serverPort: 3004,

/// total multi-thread isolate to run
totalIsolate: 3,
totalIsolate: 1,

// cors configuration
cors: CORSConfig(
allowOrigin: '*',
allowMethods: '*',
allowCredentials: true,
origin: '*',
methods: '*',
credentials: true,
),

/// response handler
Expand Down
21 changes: 14 additions & 7 deletions packages/dox-websocket/test/config/router.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import 'package:dox_core/dox_core.dart';
import 'package:dox_websocket/dox_websocket.dart';

class WsController {
intro(WebsocketEmitter emitter, dynamic message) {
emitter.emit('intro', message);
}

json(WebsocketEmitter emitter, dynamic message) {
emitter.emit('json', message);
}
}

class WebsocketRouter implements Router {
@override
List get middleware => [];
Expand All @@ -10,14 +20,11 @@ class WebsocketRouter implements Router {

@override
void register() {
Route.websocket('ws', (WebsocketEvent event) {
event.on('intro', (WebsocketEmitter emitter, dynamic message) {
emitter.room('ws').emit('intro', message);
});
WsController wsController = WsController();

event.on('json', (WebsocketEmitter emitter, dynamic message) {
emitter.emitExceptSender('json', message);
});
Route.websocket('ws', (WebsocketEvent event) {
event.on('intro', wsController.intro);
event.on('json', wsController.json);
});
}
}
39 changes: 10 additions & 29 deletions packages/dox-websocket/test/dox_websocket_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ void main() {
WebSocket socket =
await WebSocket.connect('ws://localhost:${appConfig.serverPort}/ws');

socket.listen((dynamic message) {
Map<String, dynamic> data = JSON.parse(message);
if (data['event'] == 'intro') {
expect(data['message'], 'hello');
}
if (data['event'] == 'json') {
expect(data['message']['title'], 'hello');
}
});

String data = jsonEncode(<String, String>{
'event': 'intro',
'message': 'hello',
Expand All @@ -51,41 +61,12 @@ void main() {
'message': <String, String>{'title': 'hello'}
});

socket.listen((dynamic message) {
Map<String, dynamic> data = JSON.parse(message);
if (data['event'] == 'intro') {
expect(data['message'], 'hello');
}
});

socket.add(data);
socket.add(jsonData);

WebSocket socket2 =
await WebSocket.connect('ws://localhost:${appConfig.serverPort}/ws');

String joinRoomData = jsonEncode(<String, String>{
'event': 'joinRoom',
'message': 'ws',
});

socket2.add(joinRoomData);

socket2.listen((dynamic message) {
Map<String, dynamic> data = JSON.parse(message);
if (data['event'] == 'intro') {
expect(data['message'], 'hello');
}

if (data['event'] == 'json') {
expect(data['message']['title'], 'hello');
}
});

await Future<void>.delayed(Duration(seconds: 2));

await socket.close();
await socket2.close();
});
});
}

0 comments on commit ee45756

Please sign in to comment.