aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/WebSocket/FleckWebSocket.cs
blob: 3667fab0705de52138439fc487e0e754b31d0c5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Net;
using System;
using System.Threading;
using System.Threading.Tasks;
using IWebSocketConnection = Fleck.IWebSocketConnection;

namespace MediaBrowser.Server.Implementations.WebSocket
{
    public class FleckWebSocket : IWebSocket
    {
        private readonly IWebSocketConnection _connection;

        public FleckWebSocket(IWebSocketConnection connection)
        {
            _connection = connection;

            _connection.OnMessage = OnReceiveData;
        }

        public WebSocketState State
        {
            get { return _connection.IsAvailable ? WebSocketState.Open : WebSocketState.Closed; }
        }

        private void OnReceiveData(string data)
        {
            if (OnReceive != null)
            {
                OnReceive(data);
            }
        }

        public Task SendAsync(byte[] bytes, WebSocketMessageType type, bool endOfMessage, CancellationToken cancellationToken)
        {
            return Task.Run(() => _connection.Send(bytes));
        }

        public void Dispose()
        {
            _connection.Close();
        }

        public Action<byte[]> OnReceiveBytes { get; set; }
        public Action<string> OnReceive { get; set; }
    }
}