Skip to content

Commit 0456192

Browse files
committed
Refactor to Connect and ConnectAsync
1 parent 557af34 commit 0456192

File tree

4 files changed

+66
-38
lines changed

4 files changed

+66
-38
lines changed

Realtime/Client.cs

Lines changed: 51 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -130,9 +130,11 @@ public static Client Initialize(string realtimeUrl, ClientOptions options = null
130130

131131
/// <summary>
132132
/// Attempts to connect to the socket given the params specified in `Initialize`
133+
///
134+
/// Returns when socket has successfully connected.
133135
/// </summary>
134136
/// <returns></returns>
135-
public Task<Client> Connect()
137+
public Task<Client> ConnectAsync()
136138
{
137139
var tsc = new TaskCompletionSource<Client>();
138140

@@ -180,6 +182,48 @@ public Task<Client> Connect()
180182
return tsc.Task;
181183
}
182184

185+
/// <summary>
186+
/// Attempts to connect to the socket given the params specified in `Initialize`
187+
///
188+
/// Provides a callback for `Task` driven returns.
189+
/// </summary>
190+
/// <param name="callback"></param>
191+
/// <returns></returns>
192+
public Client Connect(Action<Client> callback = null)
193+
{
194+
if (Socket != null)
195+
{
196+
Debug.WriteLine("Socket already exists.");
197+
return this;
198+
}
199+
200+
EventHandler<SocketStateChangedEventArgs> cb = null;
201+
cb = (object sender, SocketStateChangedEventArgs args) =>
202+
{
203+
switch (args.State)
204+
{
205+
case SocketStateChangedEventArgs.ConnectionState.Open:
206+
Socket.StateChanged -= cb;
207+
callback?.Invoke(this);
208+
break;
209+
case SocketStateChangedEventArgs.ConnectionState.Close:
210+
case SocketStateChangedEventArgs.ConnectionState.Error:
211+
Socket.StateChanged -= cb;
212+
throw new Exception("Error occurred connecting to Socket. Check logs.");
213+
}
214+
};
215+
216+
Socket = new Socket(realtimeUrl, Options);
217+
218+
Socket.StateChanged += HandleSocketStateChanged;
219+
Socket.OnMessage += HandleSocketMessage;
220+
221+
Socket.StateChanged += cb;
222+
Socket.Connect();
223+
224+
return this;
225+
}
226+
183227
/// <summary>
184228
/// Disconnects from the socket server (if connected).
185229
/// </summary>
@@ -188,22 +232,14 @@ public Task<Client> Connect()
188232
/// <returns></returns>
189233
public Client Disconnect(CloseStatusCode code = WebSocketSharp.CloseStatusCode.Normal, string reason = "Programmatic Disconnect")
190234
{
191-
try
192-
{
193-
if (Socket != null)
194-
{
195-
Socket.StateChanged -= HandleSocketStateChanged;
196-
Socket.OnMessage -= HandleSocketMessage;
197-
Socket.Disconnect(code, reason);
198-
Socket = null;
199-
}
200-
return this;
201-
}
202-
catch (Exception ex)
235+
if (Socket != null)
203236
{
204-
Debug.WriteLine($"Failed to disconnect socket.");
205-
throw ex;
237+
Socket.StateChanged -= HandleSocketStateChanged;
238+
Socket.OnMessage -= HandleSocketMessage;
239+
Socket.Disconnect(code, reason);
240+
Socket = null;
206241
}
242+
return this;
207243
}
208244

209245
/// <summary>

Realtime/Socket.cs

Lines changed: 13 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -86,30 +86,22 @@ public void Connect()
8686
{
8787
if (connection != null && connection.IsAlive) return;
8888

89-
try
89+
if (connection == null)
9090
{
91-
if (connection == null)
92-
{
93-
connection = new WebSocket(endpointUrl);
94-
95-
if (endpointUrl.Contains("wss"))
96-
connection.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12;
91+
connection = new WebSocket(endpointUrl);
9792

98-
connection.EnableRedirection = true;
99-
connection.WaitTime = options.LongPollerTimeout;
100-
connection.OnOpen += OnConnectionOpened;
101-
connection.OnMessage += OnConnectionMessage;
102-
connection.OnError += OnConnectionError;
103-
connection.OnClose += OnConnectionClosed;
104-
}
93+
if (endpointUrl.Contains("wss"))
94+
connection.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12;
10595

106-
connection.Connect();
107-
}
108-
catch (Exception ex)
109-
{
110-
Debug.WriteLine(ex.Message);
111-
throw ex;
96+
connection.EnableRedirection = true;
97+
connection.WaitTime = options.LongPollerTimeout;
98+
connection.OnOpen += OnConnectionOpened;
99+
connection.OnMessage += OnConnectionMessage;
100+
connection.OnError += OnConnectionError;
101+
connection.OnClose += OnConnectionClosed;
112102
}
103+
104+
connection.Connect();
113105
}
114106

115107
/// <summary>
@@ -209,7 +201,7 @@ private void OnConnectionMessage(object sender, MessageEventArgs args)
209201
{
210202
options.Decode(args.Data, decoded =>
211203
{
212-
options.Logger("receive", $"{decoded.Payload} {decoded.Topic} {decoded.Event} ({decoded.Ref})", null);
204+
options.Logger("receive", $"{args.Data} {decoded.Topic} {decoded.Event} ({decoded.Ref})", null);
213205

214206
// Ignore sending heartbeat event to `OnMessage` handler
215207
if (decoded.Ref == pendingHeartbeatRef) return;

RealtimeExample/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ static async Task Main(string[] args)
1919
realtimeClient.OnClose += (s, args) => Console.WriteLine("CLOSED");
2020
realtimeClient.OnError += (s, args) => Console.WriteLine("ERROR");
2121

22-
await realtimeClient.Connect();
22+
await realtimeClient.ConnectAsync();
2323

2424
// Subscribe to a channel and events
2525
var channelUsers = realtimeClient.Channel("realtime", "public", "users");

RealtimeTests/API.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ public API()
2828
[TestInitialize]
2929
public async Task InitializeTest()
3030
{
31-
await SocketClient.Connect();
31+
await SocketClient.ConnectAsync();
3232
}
3333

3434
[TestCleanup]

0 commit comments

Comments
 (0)