public async Task ConnectWebSocket(OnMessageHandler onMessageHandler, OnConnectHandler onConnectHandler = null, OnCloseHandler onCloseHandler = null) { await Task.Run(async() => { if (!Guid.TryParse(wsToken, out _)) { throw new ArgumentException("tokenの値が不正です, UUID形式で入力してください"); } sakuraioSocket = new ClientWebSocket(); try { await sakuraioSocket.ConnectAsync(new Uri("wss://api.sakura.io/ws/v1/" + wsToken), CancellationToken.None); } catch (System.Net.WebSockets.WebSocketException) { throw new WebSocketException("WebSocketの接続に失敗しました"); } // 特に指定がなければ呼ばない onConnectHandler?.Invoke(true); while (sakuraioSocket.State == WebSocketState.Open) { var buff = new ArraySegment <byte>(new byte[MessageBufferSize]); var ret = await sakuraioSocket.ReceiveAsync(buff, CancellationToken.None); if (!ret.EndOfMessage) { continue; } var frameString = (new UTF8Encoding()).GetString(buff.Take(ret.Count).ToArray()); Console.WriteLine(frameString); var cmsg = DeserializeChannelMessage(frameString); if (cmsg == null) { continue; } onMessageHandler(cmsg); } onCloseHandler?.Invoke(); }); }
public bool Start() { if (!check()) { return(false); } // opendSocks5Client.OnDataReceived += OpendSocks5Client_OnDataReceived; opendSocks5Client.OnDisconnected += OpendSocks5Client_OnDisconnected; logger.Info(this.GetHashCode() + "=>" + (opendSocks5Client.Client.Sock.LocalEndPoint as IPEndPoint) + "<->" + (opendSocks5Client.Client.Sock.RemoteEndPoint as IPEndPoint)); CachedTasks = new[] { Task.Run(() => { while (true) { LoopTranClient(); } logger.Info("opendSocks5Client:" + opendSocks5Client.Connected + ""); }, source.Token) .ContinueWith((x, y) => { var args = (y as List <object>); logger.Info("closing client"); if (x.IsFaulted) { args.Add(x.Exception); } }, tmpArgs), Task.Run(() => { while (!this.breakLoopTrace) { LoopTran(); } logger.Info("opendSocket:" + this.opendSocket.Connected + ""); }, source.Token) .ContinueWith((x, y) => { var args = (y as List <object>); //(args[1] as Socks5Client)?.Close(); logger.Info("closing socket"); //OnCloseHandler?.Invoke(this, new AdapterOnCloseEventArgs() //{ // S = (args[0] as Socket), // Client = (args[1] as Socks5Client), // Adapter = this //}); if (x.IsCanceled) { } else if (x.IsFaulted) { args.Add(x.Exception); } }, tmpArgs) }; Task.WhenAll(CachedTasks).ContinueWith(x => { this.opendSocket.Shutdown(SocketShutdown.Both); this.opendSocks5Client.Client.Sock.Shutdown(SocketShutdown.Both); this.opendSocket.Close(); this.opendSocks5Client.Close(); OnCloseHandler?.Invoke(this, new AdapterOnCloseEventArgs() { S = this.opendSocket, Client = this.opendSocks5Client, Adapter = this }); }); return(true); }
protected override void OnClose() { base.OnClose(); onClose?.Invoke(); }