/// <summary> /// Initiates the connection to the app /// </summary> /// <returns>An async Task</returns> /// <exception cref="Exception">Thrown if the connection is refused</exception> public async Task Connect() { if (SocketId != null) { return; } ConnectCompletionSource = new TaskCompletionSource <bool>(); uint nonce = Packet.WatchNonce(async pk => { await Task.Run(() => { TcpCSSocketControl control = new TcpCSSocketControl(pk); SocketId = control.SocketId; EP.Connections.Add(IdToString(control.SocketId), this); Requestor = true; Stream = new NRStream(this); if (control.CheckFlag(TcpCSSocketControl.Close)) { ConnectCompletionSource.SetResult(false); } }); }); EP.TransmitRaw(new TcpCOpenSocket(InstanceId, nonce)); bool success = await ConnectCompletionSource.Task; if (!success) { await Close(false); throw new Exception("Connect to distant end was refused."); } }
/// <summary> /// Closes the connection /// </summary> /// <param name="sendPack">Whether to send the payload. Usually this is true.</param> public async Task Close(bool sendPack = true) { await Task.Run(() => { if (!Open) { return; } Open = false; if (sendPack) { TcpCSSocketControl control = new TcpCSSocketControl(SocketId, TcpCSSocketControl.Close); EP.TransmitRaw(control); } if (Stream != null && Stream.IsOpen) { Stream.Close(); } EP.Connections.Remove(IdToString(SocketId)); }); }
internal async Task SendRaw(byte[] bytes) { var pa = new TcpCSSocketData(SocketId, bytes); await Task.Run(() => EP.TransmitRaw(pa)); }