using InABox.Core; using WebSocketSharp; using WebSocketSharp.Server; using ErrorEventArgs = WebSocketSharp.ErrorEventArgs; namespace InABox.Rpc { public class RpcServerSocketConnection: WebSocketBehavior { public RpcServerSocketTransport? Transport { get; set; } protected override void OnOpen() { base.OnOpen(); Transport?.ConnectionOpened(this); } protected override void OnClose(CloseEventArgs e) { base.OnClose(e); Transport?.ConnectionClosed(this,e); } protected override void OnError(ErrorEventArgs e) { base.OnError(e); Transport?.ConnectionException(this, e.Exception); } protected override void OnMessage(MessageEventArgs e) { base.OnMessage(e); Task.Run(() => { RpcMessage? request = null; if (e.IsBinary && (e.RawData != null)) request = Serialization.ReadBinary(e.RawData, BinarySerializationSettings.Latest); else if (e.IsText && !String.IsNullOrWhiteSpace(e.Data)) request = Serialization.Deserialize(e.Data); RpcMessage? response = Transport?.DoMessage(this, request); if (response != null) { if (e.IsBinary) Send(Serialization.WriteBinary(response, BinarySerializationSettings.Latest)); else { Send(Serialization.Serialize(response)); } } }); } public void Send(RpcMessage message) { Send(Serialization.WriteBinary(message, BinarySerializationSettings.Latest)); } } }