forked from ElectronNET/Electron.NET
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSocketIOFacade.cs
More file actions
108 lines (92 loc) · 2.76 KB
/
SocketIOFacade.cs
File metadata and controls
108 lines (92 loc) · 2.76 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#pragma warning disable IDE0130 // Namespace does not match folder structure
// ReSharper disable once CheckNamespace
namespace ElectronNET.API;
using System;
using System.Threading.Tasks;
using ElectronNET.API.Serialization;
using SocketIO.Serializer.SystemTextJson;
using SocketIO = SocketIOClient.SocketIO;
internal class SocketIoFacade
{
private readonly SocketIO _socket;
private readonly object _lockObj = new object();
public SocketIoFacade(string uri)
{
_socket = new SocketIO(uri);
_socket.Serializer = new SystemTextJsonSerializer(ElectronJson.Options);
// Use default System.Text.Json serializer from SocketIOClient.
// Outgoing args are normalized to camelCase via SerializeArg in Emit.
}
public event EventHandler BridgeDisconnected;
public event EventHandler BridgeConnected;
public void Connect()
{
_socket.OnError += (sender, e) => { Console.WriteLine($"BridgeConnector Error: {sender} {e}"); };
_socket.OnConnected += (_, _) =>
{
Console.WriteLine("BridgeConnector connected!");
this.BridgeConnected?.Invoke(this, EventArgs.Empty);
};
_socket.OnDisconnected += (_, _) =>
{
Console.WriteLine("BridgeConnector disconnected!");
this.BridgeDisconnected?.Invoke(this, EventArgs.Empty);
};
_socket.ConnectAsync().GetAwaiter().GetResult();
}
public void On(string eventName, Action action)
{
lock (_lockObj)
{
_socket.On(eventName, _ => { Task.Run(action); });
}
}
public void On<T>(string eventName, Action<T> action)
{
lock (_lockObj)
{
_socket.On(eventName, response =>
{
var value = response.GetValue<T>();
Task.Run(() => action(value));
});
}
}
public void Once(string eventName, Action action)
{
lock (_lockObj)
{
_socket.On(eventName, _ =>
{
this.Off(eventName);
Task.Run(action);
});
}
}
public void Once<T>(string eventName, Action<T> action)
{
lock (_lockObj)
{
_socket.On(eventName, (socketIoResponse) =>
{
this.Off(eventName);
Task.Run(() => action(socketIoResponse.GetValue<T>()));
});
}
}
public void Off(string eventName)
{
lock (_lockObj)
{
_socket.Off(eventName);
}
}
public async Task Emit(string eventName, params object[] args)
{
await _socket.EmitAsync(eventName, args).ConfigureAwait(false);
}
public void DisposeSocket()
{
_socket.Dispose();
}
}