Skip to content

Commit

Permalink
typed events init
Browse files Browse the repository at this point in the history
  • Loading branch information
AyushChothe committed Jun 7, 2022
1 parent 1a1f499 commit 9f981c4
Show file tree
Hide file tree
Showing 12 changed files with 236 additions and 61 deletions.
59 changes: 56 additions & 3 deletions polo_client/example/polo_client_example.dart
Original file line number Diff line number Diff line change
@@ -1,20 +1,73 @@
import 'dart:io';

import 'package:polo_client/polo_client.dart';
import 'package:polo_client/src/polo_type.dart';

class UserType implements PoloType {
String? name;
int? age;

UserType({this.name, this.age});

@override
UserType fromMap(Map<String, dynamic> map) {
return UserType(name: map['name'], age: map['age']);
}

@override
Map<String, dynamic> toMap() {
return {'name': name, 'age': age};
}
}

void main() async {
stdout.write("Enter Room to join: ");
// String room = stdin.readLineSync() ?? "root";

// Polo Client
PoloClient client = await Polo.connect("ws://127.0.0.1:3000/chat");
PoloClient client = await Polo.connect("ws://127.0.0.1:3000/");

// PoloClient client =
// await Polo.connect("ws://polo-chat-server.herokuapp.com/");

// Future<void> getInput() async {
// stdin.listen((msg) {
// client.send('message', String.fromCharCodes(msg).trim());
// // client.send('messageToRoom',
// // {"room": room, "message": String.fromCharCodes(msg).trim()});
// });
// }

client.onConnect(() {
print("Client Connected to Server");
client.send('dynamic', "Ayush");
client.send('dynamic', 1);
client.send('dynamic', 3.14);
client.send('dynamic', true);
client.send('dynamic', [1, 2, 3]);
client.send('dynamic', {
"String": {"dynamic": true}
});
client.send<String>('message', "Hello from Client");
client.send<UserType>('userJoined', UserType(name: "Ayush", age: 22));
});

client.onDisconnect(() {
print("Client Disconnected from Server");
});

client.onEvent('message', (message) {
print("$message");
client.onEvent('dynamic', (dyn) {
stdout.writeln("Dynamic: $dyn : ${dyn.runtimeType}");
});

client.onEvent<String>('message', (message) {
stdout.writeln("Message: $message : ${message.runtimeType}");
});

client.onEvent<UserType>('userJoined', (user) {
stdout.writeln("userJoined : ${user.toMap()} : ${user.runtimeType}");
}, converter: UserType());

client.listen();
// getInput();
}
33 changes: 14 additions & 19 deletions polo_client/lib/src/polo_client_stub.dart
Original file line number Diff line number Diff line change
@@ -1,41 +1,36 @@
abstract class PoloClient {
final Map<String, void Function(dynamic)> _callbacks = {};

void Function() _onDisconnectCallback = () {};
void Function() _onConnectCallback = () {};
import 'polo_type.dart';

abstract class PoloClient {
/// Sets onConnectCallback
void onConnect(void Function() callback) => _onConnectCallback = callback;
void onConnect(void Function() callback) {
throw UnsupportedError("Platform is not Supported");
}

/// Sets onDisconnectCallback
void onDisconnect(void Function() callback) =>
_onDisconnectCallback = callback;
void onDisconnect(void Function() callback) {
throw UnsupportedError("Platform is not Supported");
}

/// Adds a Callback to an Event
void onEvent(String event, void Function(dynamic data) callback) =>
_callbacks[event] = callback;

void _emit(String event, dynamic data) =>
_callbacks.containsKey(event) ? _callbacks[event]!(data) : () {};
void onEvent<T>(String event, void Function(T data) callback,
{PoloType? converter}) {
throw UnsupportedError("Platform is not Supported");
}

/// Starts listening for messages from `PoloServer`
Future<void> listen() {
return _handleEvents();
throw UnsupportedError("Platform is not Supported");
}

/// Sends message to the Server from Client
void send(String event, dynamic data) {
void send<T>(String event, T data) {
throw UnsupportedError("Platform is not Supported");
}

/// Closes the connection to the `PoloServer`
Future<void> close() async {
throw UnsupportedError("Platform is not Supported");
}

Future<void> _handleEvents() async {
throw UnsupportedError("Platform is not Supported");
}
}

abstract class Polo {
Expand Down
29 changes: 22 additions & 7 deletions polo_client/lib/src/polo_io_client_base.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ part of 'polo_io_client_helper.dart';
/// Use `Polo.connect()` to Connect to the `PoloServer`
class PoloClient implements stub.PoloClient {
final io.WebSocket _webSocket;
final Map<String, void Function(dynamic)> _callbacks = {};
final Map<String, Function> _callbacks = {};

void Function() _onDisconnectCallback = () {};
void Function() _onConnectCallback = () {};
Expand All @@ -21,11 +21,22 @@ class PoloClient implements stub.PoloClient {

/// Adds a Callback to an Event
@override
void onEvent(String event, void Function(dynamic data) callback) =>
void onEvent<T>(String event, void Function(T data) callback,
{PoloType? converter}) {
if (converter != null) {
assert(converter is T);
_callbacks[event] = (data) {
T typedData = converter.fromMap(data) as T;
callback(typedData);
};
} else {
_callbacks[event] = callback;
}
}

void _emit(String event, dynamic data) =>
_callbacks.containsKey(event) ? _callbacks[event]!(data) : () {};
void _emit(String event, dynamic data) {
if (_callbacks.containsKey(event)) _callbacks[event]!(data);
}

/// Starts listening for messages from `PoloServer`
@override
Expand All @@ -35,8 +46,12 @@ class PoloClient implements stub.PoloClient {

/// Sends message to the Server from Client
@override
void send(String event, dynamic data) {
_webSocket.add(jsonEncode({'event': event, 'data': data}));
void send<T>(String event, dynamic data) {
if (data is PoloType) {
_webSocket.add(jsonEncode({'event': event, 'data': data.toMap()}));
} else {
_webSocket.add(jsonEncode({'event': event, 'data': data}));
}
}

/// Closes the connection to the `PoloServer`
Expand All @@ -59,7 +74,7 @@ class PoloClient implements stub.PoloClient {
} catch (e) {
print("Error: $e");
} finally {
_webSocket.close();
close();
}
}
}
1 change: 1 addition & 0 deletions polo_client/lib/src/polo_io_client_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:convert';
import 'dart:io' as io;

import './polo_client_stub.dart' as stub;
import 'polo_type.dart';

part 'polo_io_client_base.dart';

Expand Down
9 changes: 9 additions & 0 deletions polo_client/lib/src/polo_type.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
abstract class PoloType {
Map<String, dynamic> toMap() {
throw UnimplementedError();
}

PoloType fromMap(Map<String, dynamic> map) {
throw UnimplementedError();
}
}
29 changes: 22 additions & 7 deletions polo_client/lib/src/polo_web_client_base.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ part of 'polo_web_client_helper.dart';
/// Use `Polo.connect()` to Connect to the `PoloServer`
class PoloClient implements stub.PoloClient {
final html.WebSocket _webSocket;
final Map<String, void Function(dynamic)> _callbacks = {};
final Map<String, Function> _callbacks = {};

void Function() _onDisconnectCallback = () {};
void Function() _onConnectCallback = () {};
Expand All @@ -21,11 +21,22 @@ class PoloClient implements stub.PoloClient {

/// Adds a Callback to an Event
@override
void onEvent(String event, void Function(dynamic data) callback) =>
void onEvent<T>(String event, void Function(T data) callback,
{PoloType? converter}) {
if (converter != null) {
assert(converter is T);
_callbacks[event] = (data) {
T typedData = converter.fromMap(data) as T;
callback(typedData);
};
} else {
_callbacks[event] = callback;
}
}

void _emit(String event, dynamic data) =>
_callbacks.containsKey(event) ? _callbacks[event]!(data) : () {};
void _emit(String event, dynamic data) {
if (_callbacks.containsKey(event)) _callbacks[event]!(data);
}

/// Starts listening for messages from `PoloServer`
@override
Expand All @@ -35,8 +46,12 @@ class PoloClient implements stub.PoloClient {

/// Sends message to the Server from Client
@override
void send(String event, dynamic data) {
_webSocket.sendString(jsonEncode({'event': event, 'data': data}));
void send<T>(String event, T data) {
if (data is PoloType) {
_webSocket.sendString(jsonEncode({'event': event, 'data': data.toMap()}));
} else {
_webSocket.sendString(jsonEncode({'event': event, 'data': data}));
}
}

/// Closes the connection to the `PoloServer`
Expand All @@ -59,7 +74,7 @@ class PoloClient implements stub.PoloClient {
} catch (e) {
print("Error: $e");
} finally {
_webSocket.close();
close();
}
}
}
1 change: 1 addition & 0 deletions polo_client/lib/src/polo_web_client_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:convert';
import 'dart:html' as html;

import './polo_client_stub.dart' as stub;
import 'polo_type.dart';

part 'polo_web_client_base.dart';

Expand Down
54 changes: 52 additions & 2 deletions polo_server/example/polo_server_example.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,22 @@
import 'package:polo_server/polo_server.dart';
import 'package:polo_server/src/polo_type.dart';

class UserType implements PoloType {
String? name;
int? age;

UserType({this.name, this.age});

@override
UserType fromMap(Map<String, dynamic> map) {
return UserType(name: map['name'], age: map['age']);
}

@override
Map<String, dynamic> toMap() {
return {'name': name, 'age': age};
}
}

void main() async {
// Manager
Expand All @@ -11,8 +29,40 @@ void main() async {
server.onClientConnect((client) {
print("Client(${client.id}) Connected!");

client.onEvent('message',
(message) => server.broadcastFrom(client.id, 'message', message));
client.onEvent('dynamic', (dyn) {
print("Dynamic: $dyn : ${dyn.runtimeType}");
client.send('dynamic', dyn);
});

client.onEvent<String>('message', (message) {
print("$message : ${message.runtimeType}");
client.send('message', "Hello from Server");
});

client.onEvent<UserType>(
'userJoined',
(user) {
print("userJoined : ${user.toMap()} : ${user.runtimeType}");
client.send<UserType>('userJoined', user);
},
converter: UserType(),
);

// client.onEvent<String>('message',
// (message) => server.broadcastFrom(client, 'message', message));

// client.onEvent(
// 'messageToRoom',
// (payload) => server.broadcastToRoom(
// client, payload['room'], 'message', payload['message']));

// client.onEvent('joinRoom', (room) {
// client.joinRoom(room);
// });

// client.onEvent('leaveRoom', (room) {
// client.leaveRoom(room);
// });
});

server.onClientDisconnect((client) {
Expand Down
Loading

0 comments on commit 9f981c4

Please sign in to comment.