| | 1 | | using System; |
| | 2 | | using rpc_csharp.transport; |
| | 3 | |
|
| | 4 | | namespace RPC.Transports |
| | 5 | | { |
| | 6 | | public class WebSocketTransport : ITransport |
| | 7 | | { |
| | 8 | | public event Action OnCloseEvent; |
| | 9 | |
|
| | 10 | | public event Action<string> OnErrorEvent; |
| | 11 | |
|
| | 12 | | public event Action<byte[]> OnMessageEvent; |
| | 13 | |
|
| | 14 | | public event Action OnConnectEvent; |
| | 15 | |
|
| | 16 | | private DCLWebSocketService wsService; |
| | 17 | |
|
| 0 | 18 | | public WebSocketTransport() |
| | 19 | | { |
| | 20 | | // TODO: refactor websocket service to avoid the need of this reference |
| 0 | 21 | | if (WebSocketCommunication.service != null) |
| | 22 | | { |
| 0 | 23 | | OnWebSocketServiceAdded(WebSocketCommunication.service); |
| 0 | 24 | | } |
| | 25 | | else |
| | 26 | | { |
| 0 | 27 | | WebSocketCommunication.OnWebSocketServiceAdded += OnWebSocketServiceAdded; |
| | 28 | | } |
| 0 | 29 | | } |
| | 30 | |
|
| | 31 | | public void SendMessage(byte[] data) |
| | 32 | | { |
| 0 | 33 | | wsService?.SendBinary(data); |
| 0 | 34 | | } |
| | 35 | |
|
| | 36 | | public void Close() |
| | 37 | | { |
| 0 | 38 | | WebSocketCommunication.OnWebSocketServiceAdded -= OnWebSocketServiceAdded; |
| | 39 | |
|
| 0 | 40 | | if (wsService != null) |
| | 41 | | { |
| 0 | 42 | | wsService.OnConnectEvent -= OnConnect; |
| 0 | 43 | | wsService.OnMessageEvent -= OnMessage; |
| 0 | 44 | | wsService.OnErrorEvent -= OnError; |
| 0 | 45 | | wsService.OnCloseEvent -= OnClose; |
| | 46 | | } |
| 0 | 47 | | } |
| | 48 | |
|
| | 49 | | private void OnWebSocketServiceAdded(DCLWebSocketService service) |
| | 50 | | { |
| 0 | 51 | | WebSocketCommunication.OnWebSocketServiceAdded -= OnWebSocketServiceAdded; |
| 0 | 52 | | wsService = service; |
| | 53 | |
|
| 0 | 54 | | wsService.OnConnectEvent += OnConnect; |
| 0 | 55 | | wsService.OnMessageEvent += OnMessage; |
| 0 | 56 | | wsService.OnErrorEvent += OnError; |
| 0 | 57 | | wsService.OnCloseEvent += OnClose; |
| 0 | 58 | | } |
| | 59 | |
|
| | 60 | | private void OnClose() |
| | 61 | | { |
| 0 | 62 | | OnCloseEvent?.Invoke(); |
| 0 | 63 | | } |
| | 64 | |
|
| | 65 | | private void OnError(string error) |
| | 66 | | { |
| 0 | 67 | | OnErrorEvent?.Invoke(error); |
| 0 | 68 | | } |
| | 69 | |
|
| | 70 | | private void OnMessage(byte[] message) |
| | 71 | | { |
| 0 | 72 | | OnMessageEvent?.Invoke(message); |
| 0 | 73 | | } |
| | 74 | |
|
| | 75 | | private void OnConnect() |
| | 76 | | { |
| 0 | 77 | | OnConnectEvent?.Invoke(); |
| 0 | 78 | | } |
| | 79 | | } |
| | 80 | | } |