/// <summary> /// Asynchronously connects to a server and returns an instance of <see cref="Client"/> /// </summary> /// <param name="serverUri">The server to connect</param> /// <returns>A task resolving to a client instance</returns> public static async Task <Client> ConnectNewAsync(Uri serverUri) { if (serverUri == null) { throw new ArgumentNullException(nameof(serverUri)); } if (serverUri.Scheme != "ws") { throw new ArgumentException("URI must be a websocket URI"); } var socket = new ClientWebSocket(); try { await socket.ConnectAsync(serverUri, CancellationToken.None); } catch { ; } // TODO: right now, we're prompting the server to give us our client ID. // This kinda misses the point of sockets. // The server should give us the ID straight up, but we might miss the immediate message // because we're connecting the socket first, then attaching a messenger. // So: let's make the messenger async-attachable, and then we can ensure that we get immedately- // sent messages. var clientIdCompletionSource = new TaskCompletionSource <int>(); void Messenger_FirstMessage(object sender, WebsocketReceiveEventArgs args) { ((WebsocketMessenger)sender).MessageReceived -= Messenger_FirstMessage; try { clientIdCompletionSource.SetResult(int.Parse(args.Message)); } catch (Exception ex) { clientIdCompletionSource.SetException(ex); } } var m = new WebsocketMessenger(socket); m.MessageReceived += Messenger_FirstMessage; var output = new Client(m, await clientIdCompletionSource.Task); return(output); }
/// <summary> /// Creates a new instace of <see cref="Client"/> /// </summary> /// <param name="serverUri">The URI identifying the server</param> Client(WebsocketMessenger messenger, int clientId) { this.messenger = messenger; this.commandBuilder = new Commando.Builder(clientId); messenger.MessageReceived += Messenger_MessageReceived; }