Skip to content

Commit

Permalink
initial version for typed room.OnMessage(). refactor error codes. #113
Browse files Browse the repository at this point in the history
  • Loading branch information
endel committed Apr 16, 2020
1 parent 4e5ff83 commit 8a9fc16
Show file tree
Hide file tree
Showing 11 changed files with 60 additions and 57 deletions.
2 changes: 1 addition & 1 deletion Assets/ColyseusClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ public void RegisterRoomHandlers()
PlayerPrefs.Save();

room.OnLeave += (code) => Debug.Log("ROOM: ON LEAVE");
room.OnError += (message) => Debug.LogError(message);
room.OnError += (code, message) => Debug.LogError("ERROR, code =>" + code + ", message => " + message);
room.OnStateChange += OnStateChangeHandler;

room.OnMessage<TypeMessage>("type", (message) =>
Expand Down
2 changes: 1 addition & 1 deletion Assets/Enemy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// THIS FILE HAS BEEN GENERATED AUTOMATICALLY
// DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING
//
// GENERATED USING @colyseus/schema 0.5.34
// GENERATED USING @colyseus/schema 0.5.36
//

using Colyseus.Schema;
Expand Down
2 changes: 1 addition & 1 deletion Assets/Entity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// THIS FILE HAS BEEN GENERATED AUTOMATICALLY
// DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING
//
// GENERATED USING @colyseus/schema 0.5.34
// GENERATED USING @colyseus/schema 0.5.36
//

using Colyseus.Schema;
Expand Down
2 changes: 1 addition & 1 deletion Assets/Message.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// THIS FILE HAS BEEN GENERATED AUTOMATICALLY
// DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING
//
// GENERATED USING @colyseus/schema 0.5.34
// GENERATED USING @colyseus/schema 0.5.36
//

using Colyseus.Schema;
Expand Down
2 changes: 1 addition & 1 deletion Assets/Player.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// THIS FILE HAS BEEN GENERATED AUTOMATICALLY
// DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING
//
// GENERATED USING @colyseus/schema 0.5.34
// GENERATED USING @colyseus/schema 0.5.36
//

using Colyseus.Schema;
Expand Down
15 changes: 3 additions & 12 deletions Assets/Plugins/Colyseus/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,6 @@ public class MatchMakeResponse
public string error;
}

public class MatchMakeException : Exception
{
public int Code;
public MatchMakeException(string message, int code) : base(message)
{
Code = code;
}
}


/// <summary>
/// Colyseus.Client
Expand Down Expand Up @@ -177,10 +168,10 @@ public async Task<Room<T>> ConsumeSeatReservation<T>(MatchMakeResponse response,

var tcs = new TaskCompletionSource<Room<T>>();

void OnError(string message)
void OnError(int code, string message)
{
room.OnError -= OnError;
tcs.SetException(new Exception(message));
tcs.SetException(new MatchMakeException(code, message));
};

void OnJoin()
Expand Down Expand Up @@ -249,7 +240,7 @@ protected async Task<Room<T>> CreateMatchMakeRequest<T>(string method, string ro
var response = JsonUtility.FromJson<MatchMakeResponse>(req.downloadHandler.text);
if (!string.IsNullOrEmpty(response.error))
{
throw new MatchMakeException(response.error, response.code);
throw new MatchMakeException(response.code, response.error);
}

return await ConsumeSeatReservation<T>(response, headers);
Expand Down
4 changes: 2 additions & 2 deletions Assets/Plugins/Colyseus/Protocol.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ public class Protocol
/// <summary>When JOIN request is accepted.</summary>
public static byte JOIN_ROOM = 10;

/// <summary>When JOIN request is not accepted.</summary>
public static byte JOIN_ERROR = 11;
/// <summary>When an error has happened in the server-side.</summary>
public static byte ERROR = 11;

/// <summary>When server explicitly removes <see cref="Client"/> from the <see cref="Room"/></summary>
public static byte LEAVE_ROOM = 12;
Expand Down
71 changes: 35 additions & 36 deletions Assets/Plugins/Colyseus/Room.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Colyseus
{
public delegate void ColyseusOpenEventHandler();
public delegate void ColyseusCloseEventHandler(NativeWebSocket.WebSocketCloseCode code);
public delegate void ColyseusErrorEventHandler(string message);
public delegate void ColyseusErrorEventHandler(int code, string message);

public interface IRoom
{
Expand Down Expand Up @@ -54,7 +54,7 @@ public class Room<T> : IRoom
/// </summary>
public event RoomOnStateChangeEventHandler OnStateChange;

protected Dictionary<string, object> OnMessageHandlers = new Dictionary<string, object>();
protected Dictionary<string, IMessageHandler> OnMessageHandlers = new Dictionary<string, IMessageHandler>();

private Schema.Decoder Decode = Schema.Decoder.GetInstance();

Expand All @@ -81,7 +81,11 @@ public void SetConnection (Connection connection)
Connection = connection;

Connection.OnClose += (code) => OnLeave?.Invoke(code);
Connection.OnError += (message) => OnError?.Invoke(message);

// TODO: expose WebSocket error code!
// Connection.OnError += (code, message) => OnError?.Invoke(code, message);

Connection.OnError += (message) => OnError?.Invoke(0, message);
Connection.OnMessage += (bytes) => ParseMessage(bytes);
}

Expand Down Expand Up @@ -128,40 +132,33 @@ public async Task Send (object data)
//await Connection.Send(new object[]{Protocol.ROOM_DATA, data});
}

public Listener<Action<PatchObject>> Listen(Action<PatchObject> callback)
{
if (string.IsNullOrEmpty(SerializerId))
{
throw new Exception("room.Listen() should be called after room.OnJoin");
}
return ((FossilDeltaSerializer)serializer).State.Listen(callback);
}

public Listener<Action<DataChange>> Listen(string segments, Action<DataChange> callback, bool immediate = false)
{
if (string.IsNullOrEmpty(SerializerId))
{
throw new Exception("room.Listen() should be called after room.OnJoin");
}
return ((FossilDeltaSerializer)serializer).State.Listen(segments, callback, immediate);
}

public void OnMessage<MessageType>(string type, Action<MessageType> handler)
{
OnMessageHandlers.Add(type, (new Action<object>((obj) =>
//OnMessageHandlers.Add(type, (new Action<object>((obj) =>
//{
// handler.Invoke((MessageType)obj);
//})));

OnMessageHandlers.Add(type, new MessageHandler<MessageType>
{
handler.Invoke((MessageType)obj);
})));
Action = handler
});
}

public void OnMessage<MessageType>(int type, Action<MessageType> handler)
{
OnMessageHandlers.Add("i" + type.ToString(), (new Action<object>((obj) => handler.Invoke((MessageType)obj))));
OnMessageHandlers.Add("i" + type.ToString(), new MessageHandler<MessageType>
{
Action = handler
});
}

public void OnMessage<MessageType>(MessageType type, Action<MessageType> handler) where MessageType : Schema.Schema, new()
{
OnMessageHandlers.Add("s" + type.GetType(), (new Action<object>((obj) => handler.Invoke((MessageType)obj))));
OnMessageHandlers.Add("s" + type.GetType(), new MessageHandler<MessageType>
{
Action = handler
});
}

protected async void ParseMessage (byte[] bytes)
Expand Down Expand Up @@ -195,10 +192,12 @@ protected async void ParseMessage (byte[] bytes)
// Acknowledge JOIN_ROOM
await Connection.Send(new byte[] { Protocol.JOIN_ROOM });
}
else if (code == Protocol.JOIN_ERROR)
else if (code == Protocol.ERROR)
{
var message = System.Text.Encoding.UTF8.GetString(bytes, 2, bytes[1]);
OnError?.Invoke(message);
Schema.Iterator it = new Schema.Iterator { Offset = 1 };
var errorCode = Decode.DecodeNumber(bytes, it);
var errorMessage = Decode.DecodeString(bytes, it);
OnError?.Invoke((int) errorCode, errorMessage);

}
else if (code == Protocol.ROOM_DATA_SCHEMA)
Expand All @@ -208,7 +207,7 @@ protected async void ParseMessage (byte[] bytes)
var message = (Schema.Schema) Activator.CreateInstance(messageType);
message.Decode(bytes, new Schema.Iterator { Offset = 2 });

((Action<object>) OnMessageHandlers["s" + message.GetType()])?.Invoke(message);
(OnMessageHandlers["s" + message.GetType()])?.Invoke(message);
}
else if (code == Protocol.LEAVE_ROOM)
{
Expand All @@ -227,26 +226,26 @@ protected async void ParseMessage (byte[] bytes)
}
else if (code == Protocol.ROOM_DATA)
{
Action<object> handler = null;
object type;
IMessageHandler handler;
dynamic type;

Schema.Iterator it = new Schema.Iterator { Offset = 1 };

if (Decode.NumberCheck(bytes, it))
{
type = Decode.DecodeNumber(bytes, it);
handler = (Action<object>) OnMessageHandlers["i" + type];
handler = OnMessageHandlers["i" + type];

} else
{
type = Decode.DecodeString(bytes, it);
handler = (Action<object>) OnMessageHandlers[type.ToString()];
handler = OnMessageHandlers[type.ToString()];
}

if (handler != null)
{
// TODO: de-serialize message with an offset, to avoid creating a new buffer
var message = MsgPack.Deserialize<object>(new MemoryStream(
var message = MsgPack.Deserialize(handler.Type, new MemoryStream(
// TODO: de-serialize message with an offset, to avoid creating a new buffer
ArrayUtils.SubArray(bytes, it.Offset, bytes.Length - it.Offset)
));

Expand Down
13 changes: 13 additions & 0 deletions Assets/Plugins/Colyseus/Utils/Exceptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;

namespace Colyseus
{
public class MatchMakeException : Exception
{
public int Code;
public MatchMakeException(int code, string message) : base(message)
{
Code = code;
}
}
}
2 changes: 1 addition & 1 deletion Assets/State.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// THIS FILE HAS BEEN GENERATED AUTOMATICALLY
// DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING
//
// GENERATED USING @colyseus/schema 0.5.34
// GENERATED USING @colyseus/schema 0.5.36
//

using Colyseus.Schema;
Expand Down
2 changes: 1 addition & 1 deletion Server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
},
"dependencies": {
"@colyseus/social": "^0.10.0",
"colyseus": "^0.13.0-alpha.3",
"colyseus": "^0.13.0-alpha.10",
"cors": "^2.8.5",
"express": "^4.13.3",
"express-jwt": "^5.3.1",
Expand Down

0 comments on commit 8a9fc16

Please sign in to comment.