Close() public method

Closes the WebSocket connection, and releases all associated resources.
This method does nothing if the current state of the connection is Closing or Closed.
public Close ( ) : void
return void
Example #1
1
        public int ConnectToWebSocket()
        {
            ws = new WebSocket(_Address);

            timer = new System.Windows.Forms.Timer();
            timer.Interval = 1500;
            timer.Tick += (sender, e) =>
            {
                if (ws != null)
                    ws.Send(JsonConvert.SerializeObject(new { type = "getframe" }));
            };

            ws.OnMessage += Ws_OnMessage;
            ws.OnOpen += (sender, e) =>
            {
                //ws.Send(JsonConvert.SerializeObject(new { type = "getinfo" }));
                string msg = "{\"type\":\"getinfo\"}";
                ws.Send(msg);
            };
            ws.OnError += (sender, e) =>
                {
                    MessageBox.Show("Error during Websocket Connection: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ws.Close();
                    ws = null;
                    this.Dispose();
                };

            ws.Connect();
            if (Connected != null)
                Connected();
            timer.Start();

            return 0;
        }
Example #2
0
 private void WebSocket_OnClose(object sender, CloseEventArgs e)
 {
     _logger.LogDebug("Close request received");
     _webSocket?.Close();
     IsStreaming = false;
     RaiseCloseEvent();
 }
Example #3
0
        public void InitServerInfo(string serverIp, string serverPort)
        {
            IsOpenned = false;
            L4Logger.Info("BCR InitServerInfo");
            if (_WebSocket != null)
            {
                _WebSocket.Close();
                _WebSocket.OnMessage -= _WebSocket_OnMessage;
            }
            this.ServerIP   = serverIp;
            this.ServerPort = serverPort;

            _WebSocket            = new WebSocketSharp.WebSocket(string.Format("ws://{0}:{1}/XfsCommandBehavior", ServerIP, ServerPort));
            _WebSocket.OnMessage += _WebSocket_OnMessage;
            _WebSocket.OnClose   += _WebSocket_OnClose;
            _WebSocket.OnError   += _WebSocket_OnError;
            _WebSocket.Connect();

            ReadDataCompleted = null;
            ReadDataError     = null;
            OpenCompleted     = null;
            RegisterCompleted = null;
            OpenError         = null;
            RegisterError     = null;
        }
Example #4
0
 private void Socket_OnError(object sender, ErrorEventArgs e)
 {
     try
     {
         logger.Error("Socket_OnError, ErrorEventArgs = " + JsonConvert.SerializeObject(e));
         socket.Close(CloseStatusCode.Normal);   //  触发OnClose事件
     }
     catch (Exception ex)
     {
         logger.Error("socket_OnError args = " + JsonConvert.SerializeObject(e) + "\n" + ex.ToString());
     }
 }
Example #5
0
        /// <summary>
        /// Close socket
        /// </summary>
        public void Clear()
        {
            logger.Trace("");

            if (socket == null)
            {
                return;
            }

            try
            {
                if (socket.ReadyState == WebSocketState.Open)
                {
                    socket.Close();
                }

                socket.OnOpen    -= Socket_OnOpen;
                socket.OnClose   -= Socket_OnClose;
                socket.OnError   -= Socket_OnError;
                socket.OnMessage -= Socket_OnMessage;

                socket = null;
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "WebSocket Clear Exception");
            }
        }
Example #6
0
 public void Disconnect()
 {
     if (_webSocket != null)
     {
         _webSocket.Close();
     }
 }
 public void disconnect()
 {
     if (webSocket != null)
     {
         webSocket.Close();
     }
 }
 public void OnApplicationQuit()
 {
     if (m_ws != null && m_ws.ReadyState == WebSocketState.Open)
     {
         m_ws.Close();
     }
 }
Example #9
0
 /// <summary>
 /// Close the current WebSocket connection.
 /// </summary>
 public override void Close()
 {
     if (isConnected)
     {
         webSocketSharp.Close();
     }
 }
 /// <summary>
 /// Disconnects the WebSocket connection.
 /// </summary>
 /// <param name="e">Disconect event arguments.</param>
 /// <returns></returns>
 public override Task DisconnectAsync(SocketCloseEventArgs e)
 {
     if (_socket.IsAlive)
     {
         _socket.Close();
     }
     return(Task.Delay(0));
 }
Example #11
0
 private static void Ws_OnError(object sender, ErrorEventArgs e)
 {
     Console.WriteLine("Exception on socket stream : {0}", e.Message);
     ws.Close();
     ws = new WebSocketSharp.WebSocket("ws://localhost:1346/CandleMarket");
     ws.Connect();
     ws.OnMessage += Ws_OnMessage;
     ws.OnClose   += Ws_OnClose;
     ws.OnError   += Ws_OnError;
 }
Example #12
0
        public async Task StreamAsync(Uri uri, CancellationToken token)
        {
            Throw.IfNull(uri, nameof(uri));

            if (!token.CanBeCanceled)
            {
                throw new ArgumentException("Token must be capable of being in the canceled state.", nameof(token));
            }

            token.ThrowIfCancellationRequested();

            IsStreaming = true;

            _webSocket            = new WebSocketSharp.WebSocket(uri.ToString());
            _webSocket.EmitOnPing = true;
            _webSocket.WaitTime   = TimeSpan.FromSeconds(30);

            _webSocket.OnMessage += WebSocket_OnMessage;
            _webSocket.OnError   += WebSocket_OnError;
            _webSocket.OnClose   += WebSocket_OnClose;

            try
            {
                try
                {
                    _webSocket.Connect();

                    if (_webSocket.ReadyState == WebSocketState.Open)
                    {
                        RaiseOpenEvent();
                    }
                }
                catch (OperationCanceledException) { }
                catch (Exception e)
                {
                    if (!token.IsCancellationRequested)
                    {
                        _logger?.LogError(e, $"{nameof(WebSocketClient)}.{nameof(StreamAsync)}: WebSocket connect exception.");
                        throw;
                    }
                }
            }
            finally
            {
                IsStreaming = false;

                // NOTE: WebSocketState.CloseSent should not be encountered since CloseOutputAsync is not used.
                if (_webSocket.ReadyState == WebSocketState.Open || _webSocket.ReadyState == WebSocketState.Closing)
                {
                    _webSocket.Close();
                }

                RaiseCloseEvent();
            }
        }
Example #13
0
 public override void Dispose()
 {
     if (IsServer)
     {
         Server.Stop();
     }
     else
     {
         Client.Close();
     }
 }
Example #14
0
 private void Websocket_OnError(object sender, ErrorEventArgs e)
 {
     Console.WriteLine("Error:" + e.Exception.Message.ToString());
     Console.WriteLine("websocket.IsAlive:" + websocket.IsAlive);
     Log4NetUtility.Debug("OnError", "websocket.IsAlive:" + websocket.IsAlive);
     Log4NetUtility.Debug("OnError", e.Exception.Message);
     if (!websocket.IsAlive)
     {
         websocket.Close();
     }
 }
 public void Dispose()
 {
     if (null == _webSocket)
     {
         return;
     }
     if (_webSocket.ReadyState == WebSocketState.Open)
     {
         _webSocket.Close();
     }
     //_webSocket.Dispose();
 }
 public void Close()
 {
     if (webSocket.IsAlive)
     {
         var json = requestAgent.CreateDisconnectAllJson();
         webSocket.Send(json);
     }
     webSocket.OnOpen    -= OnWebSocketOpen;
     webSocket.OnMessage -= OnWebSocketMessageReceive;
     webSocket.OnError   -= OnWebSocketError;
     webSocket.OnClose   -= OnWebSocketClose;
     webSocket.Close();
 }
Example #17
0
        public void Disconnect()
        {
            if (_webSocket != null)
            {
                _webSocket.OnOpen    -= Websocket_OnOpen;
                _webSocket.OnMessage -= Websocket_OnMessage;
                _webSocket.OnClose   -= _webSocket_OnClose;
                _webSocket.OnError   -= _webSocket_OnError;

                _webSocket.Close();

                _webSocket   = null;
                _isConnected = false;
            }
        }
Example #18
0
        public void close()
        {
            if (heartbeatTimer != null)
            {
                heartbeatTimer.Dispose();
                heartbeatTimer = null;
            }

            if (websocket != null)
            {
                websocket.Close();
                websocket = null;
            }

            bIsRunning = false;
        }
Example #19
0
 public void Close()
 {
     if (ws != null)
     {
         try
         {
             log.Debug(this.uri.ToString() + ": Closing connection");
             ws.Close();
         }
         catch (Exception ex)
         {
             log.Error("Failed to close connection with client", ex);
         }
     }
     ws = null;
 }
Example #20
0
        public void Close()
        {
            if (null == socket)
            {
                return;
            }

            RemoveEvents();

            if (false == IsConnected())
            {
                socket = null;
                return;
            }

            socket.Close();
            socket = null;

            StopRecvPolling();
        }
        public void Close(CloseStatusCode code = CloseStatusCode.Normal, string reason = null)
        {
            if (ReadyState == WebSocketSharp.WebSocketState.Closing)
            {
                throw new InvalidOperationException("Socket is already closing");
            }

            if (ReadyState == WebSocketSharp.WebSocketState.Closed)
            {
                throw new InvalidOperationException("Socket is already closed");
            }

            try
            {
                Connection.Close(code, reason);
            }
            catch (Exception e)
            {
                throw new WebSocketException("Could not close socket", e);
            }
        }
        public WebSocketClientService(string url, ILogger logger, string origin = null, string serviceName = null) : base(serviceName)
        {
            RegisterWaitHandle(ping, PingTick);
            RegisterWaitHandle(open, Ws_OnOpen);
            RegisterWaitHandle(close, Ws_OnClose);
            Logger        = logger;
            serverAddress = url;

            ws = new WebSocketSharp.WebSocket(url)
            {
                Origin = origin,
            };

            ws.OnOpen    += (a, e) => open.Set();
            ws.OnClose   += (a, e) => close.Set();
            ws.OnError   += Ws_OnError;
            ws.OnMessage += Ws_OnMessage;

            connection = new ConnectionTracker(() => ws.Connect(), () => ws.Close());

            pingTimer = new Timer(o => ping.Set(), null, Timeout.Infinite, Timeout.Infinite);
        }
        public void EnableSubscribe(bool flag)
        {
            if (flag)
            {
                DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                TimeSpan diff   = DateTime.Now.ToUniversalTime() - origin;
                long     nonce  = (long)Math.Floor(diff.TotalMilliseconds);

                var    authPayload     = $"AUTH{nonce}";
                var    hmac            = new HMACSHA384(Encoding.UTF8.GetBytes(Global.API_SECRET_KEY));
                byte[] k               = hmac.ComputeHash(Encoding.UTF8.GetBytes(authPayload));
                string signatureString = string.Concat(k.Select(b => b.ToString("X2")).ToArray()).ToLower();

                dynamic payload = new System.Dynamic.ExpandoObject();
                payload.apiKey      = Global.API_PUBLIC_KEY;
                payload.authSig     = signatureString;
                payload.authNonce   = nonce;
                payload.authPayload = authPayload;
                ((IDictionary <string, object>)payload)["event"] = "auth";
                payload.filter = new List <dynamic>();
                payload.filter.Add("trading");
                payload.filter.Add("wallet");
                payload.filter.Add("balance");

                _subscribeWS            = new WebSocketSharp.WebSocket("wss://api.bitfinex.com/ws/2");
                _subscribeWS.OnMessage += (sender, e) => this.SubscribeFunc(e.Data);
                _subscribeWS.Connect();
                _subscribeWS.Send(JsonConvert.SerializeObject(payload));
            }
            else
            {
                _subscribeWS.Close();
                _subscribeWS = null;

                this.ActionWalletSnapshot(new List <dynamic>());
                this.ActionOrderSnapshot(new List <dynamic>());
                this.ActionPositionSnapshot(new List <dynamic>());
            }
        }
Example #24
0
        public bool Down()
        {
            bool isConnected = false;

            try
            {
                if (_clientWebSocket != null && Status == NetStatus.Connected)
                {
                    _clientWebSocket.Close();
                    isConnected = _clientWebSocket.IsAlive;
                    Status      = isConnected ? NetStatus.Connected : NetStatus.Disconnected;
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(LogType.Error, $"NetworkWSSClient| Down", $"{ex.Message}");
                return(false);
            }

            return(isConnected);
        }
Example #25
0
        static void Main(string[] args)
        {
            Logger.LogLevel          = LogLevel.Info;
            Logger.ShortenSourceName = true;
            Logger.ShowTime          = false;

            /*
             * for (int i = 0; i <= 4; i++)
             * {
             *  Logger.LogLevel = (LogLevel)i;
             *  Console.WriteLine($"LogLevel is {Logger.LogLevel.ToString()}");
             *  Logger.Trace("Trace test");
             *  Logger.Debug("Debug test");
             *  Logger.Info("Info test");
             *  Logger.Warning("Warning test");
             *  Logger.Error("Error test");
             *  Logger.Exception("Exception test", new Exception());
             * }
             */
            Logger.Info("Starting Command-Server");
            Plugins       = new List <ICommandPlugin>();
            Plugins       = LoadPlugins();
            ws            = new WebSocketSharp.WebSocket(bsUrl);
            ws.Log.Output = (_, __) => { }; // Disable error output
            ws.OnMessage += OnMessage;

            /*
             * ws.OnClose += (s, e) => {
             *  Logger.Info($"Disconnected");
             * };
             */
            TryConnect();
            Console.ReadKey(true);
            ws.Close();
            Console.ReadKey(true);
        }
 public void Disconnect()
 {
     _wss.Close(CloseStatusCode.Away);
     _logger.Info($"Connection close");
 }
Example #27
0
 public void Close()
 {
     m_Socket.Close();
 }
Example #28
0
 public void Dispose()
 {
     Client.Close();
     this.HDEHost.MainLoop.OnPrepareGraph -= this.ClearBuffers;
     this.HDEHost.MainLoop.OnUpdateView   -= this.IncrementAge;
 }
Example #29
0
        private static WebSocket GetClient(ServantConfiguration configuration)
        {
            var url = "ws://" + configuration.ServantIoUrl + "/Client?installationGuid=" + configuration.InstallationGuid + "&organizationGuid=" + configuration.ServantIoKey + "&servername=" + System.Environment.MachineName;
            using (var ws = new WebSocket(url))
            {
                var serializer = new JavaScriptSerializer();
                var pingTimer = new System.Timers.Timer(2000);
                pingTimer.Elapsed += (sender, args) =>
                                     {
                                         ws.Ping();
                                     };
                pingTimer.Enabled = false;

                ws.OnMessage += (sender, e) =>
                {
                    var request = serializer.Deserialize<CommandRequest>(e.Data);

                    switch (request.Command)
                    {
                        case CommandRequestType.Unauthorized:
                            IsStopped = true;
                            Console.WriteLine();
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Servant.io key was not recognized.");
                            Console.ResetColor();
                            ws.Close();
                            break;
                        case CommandRequestType.GetSites:
                            var sites = SiteManager.GetSites();
                            var result = serializer.Serialize(sites);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid)
                                                     {
                                                         Guid = request.Guid,
                                                         Message = result,
                                                         Success = true
                                                     }));
                            break;
                        case CommandRequestType.UpdateSite:
                            var site = serializer.Deserialize<Site>(request.JsonObject);

                            var originalSite = SiteManager.GetSiteByName(request.Value);

                            if (originalSite == null)
                            {
                                ws.Send("not_found");
                                return;
                            }

                            originalSite.ApplicationPool = site.ApplicationPool;
                            originalSite.Name = site.Name;
                            originalSite.SiteState = site.SiteState;
                            originalSite.Bindings = site.Bindings;
                            originalSite.LogFileDirectory = site.LogFileDirectory;
                            originalSite.SitePath = site.SitePath;
                            originalSite.Bindings = site.Bindings;

                            SiteManager.UpdateSite(originalSite);

                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message  = "ok", Success = true}));
                            break;
                        case CommandRequestType.GetApplicationPools:
                            var appPools = SiteManager.GetApplicationPools();
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) {Message = serializer.Serialize(appPools), Success = true}));
                            break;
                        case CommandRequestType.GetCertificates:
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) {Message = serializer.Serialize(SiteManager.GetCertificates()), Success = true}));
                            break;
                        case CommandRequestType.StartSite:
                            var startSite = SiteManager.GetSiteByName(request.Value);
                            var startResult = SiteManager.StartSite(startSite);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Success = startResult == SiteStartResult.Started, Message = startResult.ToString() }));
                            break;
                        case CommandRequestType.StopSite:
                            var stopSite = SiteManager.GetSiteByName(request.Value);
                            SiteManager.StopSite(stopSite);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) {  Success = true }));
                            break;
                        case CommandRequestType.RecycleApplicationPool:
                            var recycleSite = SiteManager.GetSiteByName(request.Value);
                            SiteManager.RecycleApplicationPoolBySite(recycleSite.IisId);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = "ok", Success = true }));
                            break;
                        case CommandRequestType.RestartSite:
                            var restartSite = SiteManager.GetSiteByName(request.Value);
                            SiteManager.RestartSite(restartSite.IisId);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = "ok", Success = true }));
                            break;
                        case CommandRequestType.DeleteSite:
                            var deleteSite = SiteManager.GetSiteByName(request.Value);
                            SiteManager.DeleteSite(deleteSite.IisId);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = "ok", Success = true }));
                            break;
                        case CommandRequestType.CreateSite:
                            var createSite = serializer.Deserialize<Site>(request.JsonObject);
                            var id = SiteManager.CreateSite(createSite);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = id.ToString(), Success = true }));
                            break;
                    }
                };

                ws.OnError += (sender, args) =>
                {
                    var isInternalError = args.Message == "An exception has occurred while receiving a message.";

                    var socket = (WebSocket)sender;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error: " + args.Message);
                    Console.ResetColor();

                    if (socket.ReadyState == WebSocketState.Open && !isInternalError)
                    {
                        Connect();
                    }
                };

                ws.OnClose += (sender, args) =>
                {
                    Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Lost connection to Servant.io");
                    pingTimer.Enabled = false;

                    if (!_isRetrying)
                    {
                        Connect();
                    }
                };

                ws.OnOpen += (sender, args) =>
                    {
                        Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Successfully connected to ws://" + configuration.ServantIoUrl);
                        pingTimer.Enabled = true;
                    };
                ws.Log.Output = (data, s) => { };
                ws.Log.Level = LogLevel.Fatal;

                return ws;
            }
        }
Example #30
0
        static private async Task StartStend()
        {
            var             autoEvent        = new AutoResetEvent(false);
            bool            video_translator = true;
            bool            file_created     = false;
            FileStream      file             = null;
            Quartus         quartus          = Quartus.GetInstance();
            Microcontroller arduino          = Microcontroller.Create();

            if (video_translator)
            {
                // Asynchronously retrieve a list of available video capture devices (webcams).
                var deviceList = await DeviceVideoTrackSource.GetCaptureDevicesAsync();


                // For example, print them to the standard output
                foreach (var device in deviceList)
                {
                    Console.WriteLine($"Found webcam {device.name} (id: {device.id})");
                }
            }

            // Create a new peer connection automatically disposed at the end of the program
            var pc = new PeerConnection();
            // Initialize the connection with a STUN server to allow remote access
            var config = SystemConfiguration.PeerConnectionSettings;


            await pc.InitializeAsync(config);

            Console.WriteLine("Peer connection initialized.");
            //var chen = await pc.AddDataChannelAsync("sendDataChannel", true, true, cancellationToken: default);
            Console.WriteLine("Opening local webcam...");


            // pc - PeerConnection object
            Transceiver                videoTransceiver = null;
            VideoTrackSource           videoTrackSource = null;
            LocalVideoTrack            localVideoTrack  = null;
            LocalVideoDeviceInitConfig c = new LocalVideoDeviceInitConfig();

            await VideoDeviceSelection();

            videoTrackSource = await Camera.CreateAsync(SystemConfiguration.VideoDeviceSettings);


            WebSocketSharp.WebSocket signaling = new WebSocketSharp.WebSocket(CreateSignalingServerUrl(), "id_token", "alpine");
            pc.LocalSdpReadytoSend += (SdpMessage message) =>
            {
                //Console.WriteLine(SdpMessage.TypeToString(message.Type));
                Console.WriteLine(message.Content);
                //Console.WriteLine(HttpUtility.JavaScriptStringEncode(message.Content));
                Console.WriteLine("Sdp offer to send: {\"data\":{\"description\":{\"type\":\"" + SdpMessage.TypeToString(message.Type) + "\",\"sdp\":\"" + HttpUtility.JavaScriptStringEncode(message.Content) + "\"}}}");
                signaling.Send(message.ToABJson());
            };

            pc.RenegotiationNeeded += () =>
            {
                Console.WriteLine("Regotiation needed");
                bool OfferCreated = pc.CreateOffer();
                Console.WriteLine("OfferCreated? {0}", OfferCreated);
            };
            pc.DataChannelAdded += (DataChannel channel) =>
            {
                Console.WriteLine("Added data channel ID: {0}, Label: {1}; Reliable: {2}, Ordered: {3}", channel.ID, channel.Label, channel.Reliable, channel.Ordered);

                if (channel.Label == "sendDataChannel")
                {
                    channel.MessageReceived += (byte[] mess) => {
                        try
                        {
                            CTP_packet command = JsonSerializer.Deserialize <CTP_packet>(mess);
                            Console.WriteLine(arduino.SendCTP_Command(command));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    };
                }
                else
                {
                    if (file_created == false)
                    {
                        file         = new FileStream(channel.Label, FileMode.Append);
                        file_created = true;
                    }
                    channel.MessageReceived += async(byte[] mess) =>
                    {
                        // Console.WriteLine(System.Text.Encoding.Default.GetString(mess));
                        if (mess.Length == 3 && System.Text.Encoding.Default.GetString(mess) == "EOF")
                        {
                            string file_name = file.Name;
                            file.Close();
                            string t = await quartus.RunQuartusCommandAsync($"quartus_pgm -m jtag –o \"p;{file_name}@1\"");

                            File.Delete(file_name);
                            file_created = false;
                        }
                        else
                        {
                            WriteFileSegment(mess, file);
                        }
                    };
                }

                channel.StateChanged += () =>
                {
                    Console.WriteLine("State change: {0}", channel.State);
                };
            };

            pc.IceCandidateReadytoSend += (IceCandidate candidate) =>
            {
                //Console.WriteLine("Content: {0}, SdpMid: {1}, SdpMlineIndex: {2}", candidate.Content, candidate.SdpMid, candidate.SdpMlineIndex);
                try
                {
                    Console.WriteLine("Candidate to send: Content: {0}, SdpMid: {1}, SdpMlineIndex: {2}", candidate.Content, candidate.SdpMid, candidate.SdpMlineIndex);
                    signaling.Send(candidate.ToABJson());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error to send local ice candidate");
                }
            };
            //videoTrackSource.I420AVideoFrameReady += (frame) =>
            //{
            //    Console.WriteLine("Argb32 frame ready. {0} : {1}", frame.width, frame.height);
            //    Console.WriteLine("DataA: {0}, DataU: {1}, DataV: {2}, DataY: {3}", Marshal.SizeOf(frame.dataA),
            //                        Marshal.SizeOf(frame.dataU),
            //                        Marshal.SizeOf(frame.dataV),
            //                        Marshal.SizeOf(frame.dataY));
            //};

            signaling.OnMessage += async(sender, message) =>
            {
                (string header, string correct_message) = message.Data.DivideHeaderAndOriginalJSON();
                Console.WriteLine("Correct message: {0}", correct_message);
                Console.WriteLine("Header: {0}", header);
                if (header == "{\"data\":{\"getRemoteMedia\":" && correct_message == "true")
                {
                    Console.WriteLine("Create local video track...");
                    var trackSettings = new LocalVideoTrackInitConfig {
                        trackName = "webcam_track"
                    };
                    localVideoTrack = LocalVideoTrack.CreateFromSource(videoTrackSource, new LocalVideoTrackInitConfig {
                        trackName = "webcam_track"
                    });
                    Console.WriteLine("Create video transceiver and add webcam track...");
                    TransceiverInitSettings option = new TransceiverInitSettings();
                    option.Name      = "webcam_track";
                    option.StreamIDs = new List <string> {
                        "webcam_name"
                    };
                    videoTransceiver = pc.AddTransceiver(MediaKind.Video, option);
                    videoTransceiver.DesiredDirection = Transceiver.Direction.SendOnly;
                    videoTransceiver.LocalVideoTrack  = localVideoTrack;

                    bool OfferCreated = pc.CreateOffer();
                    Console.WriteLine("OfferCreated? {0}", OfferCreated);
                }
                //Console.WriteLine(message.Data);
                if (header.IndexOf("candidate") != -1 && correct_message != "null")
                {
                    try
                    {
                        var candidate = JsonSerializer.Deserialize <ICEJavaScriptNotation>(correct_message);
                        Console.WriteLine("Content of ice: {0}, SdpMid: {1}, SdpMLineIndex: {2}", candidate.candidate, candidate.sdpMid, candidate.sdpMLineIndex);
                        pc.AddIceCandidate(candidate.ToMRNetCoreNotation());
                        Console.WriteLine("Deserialized by ice_candidate");
                        //return;
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Could not deserialize as ice candidate");
                    }
                }

                if (header.IndexOf("description") != -1)
                {
                    try
                    {
                        SdpMessage received_description = JsonSerializer.Deserialize <SDPJavaScriptNotation>(correct_message).ToMRNetCoreNotation();
                        await pc.SetRemoteDescriptionAsync(received_description);

                        if (received_description.Type == SdpMessageType.Offer)
                        {
                            bool res = pc.CreateAnswer();
                            Console.WriteLine("Answer created? {0}", res);
                        }
                        Console.WriteLine("Deserialized by sdp_message");
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Could not deserialize as sdp message");
                    }
                }
            };


            pc.Connected += () =>
            {
                Console.WriteLine("Connected");
            };
            pc.IceStateChanged += (IceConnectionState newState) =>
            {
                if (newState == IceConnectionState.Disconnected)
                {
                    Console.WriteLine("Disconected");
                }
            };


            signaling.Connect();
            if (!video_translator)
            {
                signaling.Send("{\"data\":{\"getRemoteMedia\":true}}");
            }

            //Console.WriteLine("Press a key to terminate the application...");
            Console.ReadKey(true);
            Console.WriteLine("Program termined.");
            file?.Close();
            pc?.Close();
            signaling?.Close();
            //arduino?.Close();
            //(var a, var b) = ConvertString("{\"data\":{\"candidate\":null}}");
            //Console.WriteLine("{0}, {1}", a, b);
        }
        public void Start(string url = "ws://127.0.0.1:3000/socket.io/?EIO=4&transport=websocket")
        { 
            ws = new WebSocket(url);
            ws.OnOpen += (s, e) => RaiseEvent("open");
            ws.OnError += (s, e)=> RaiseEvent("error");
            ws.OnClose += (s, e) => RaiseEvent("close");
            ws.OnMessage += OnMessage;

            int reconnectDelay = 500;

            base.Start(() =>
            {
                try {
                    if (ws.IsConnected)
                    {
                        Thread.Sleep(reconnectDelay);
                    }
                    else
                    {
                        ws.Connect();
                    }
                }
                catch(ThreadAbortException)
                {
                }
            }
            , ()=>
            {
                ws.Close();
            });

        }
 public void Close(ushort?code = null, string message = null)
 {
     ws.Close();
 }
Example #33
0
        public override async Task StreamAsync(Uri uri, CancellationToken token)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (!token.CanBeCanceled)
            {
                throw new ArgumentException("Token must be capable of being in the canceled state.", nameof(token));
            }

            token.ThrowIfCancellationRequested();

            var tcs = new TaskCompletionSource <object>();

            token.Register(() => tcs.TrySetCanceled());

            var webSocket = new WebSocketSharp.WebSocket(uri.AbsoluteUri);

            webSocket.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
            webSocket.Log.Output = (d, s) => { /* ignore */ };

            webSocket.OnOpen += (s, e) =>
            {
                IsStreaming = true;
                RaiseOpenEvent();
            };

            webSocket.OnClose += (s, e) =>
            {
                tcs.TrySetCanceled();
            };

            webSocket.OnMessage += (s, evt) =>
            {
                try
                {
                    if (evt.IsText)
                    {
                        var json = evt.Data;

                        if (!string.IsNullOrWhiteSpace(json))
                        {
                            RaiseMessageEvent(new WebSocketClientEventArgs(json));
                        }
                        else
                        {
                            _logger?.LogWarning($"{nameof(WebSocketSharpClient)}.OnMessage: Received empty JSON message.");
                        }
                    }
                }
                catch (OperationCanceledException) { }
                catch (Exception e)
                {
                    if (!token.IsCancellationRequested)
                    {
                        _logger?.LogError(e, $"{nameof(WebSocketSharpClient)}.OnMessage: WebSocket read exception.");
                        throw;
                    }
                }
            };

            Exception exception = null;

            webSocket.OnError += (s, e) =>
            {
                if (!token.IsCancellationRequested)
                {
                    _logger?.LogError(e.Exception, $"{nameof(WebSocketSharpClient)}.OnError: WebSocket exception.");
                    exception = e.Exception;
                    tcs.TrySetCanceled();
                }
            };

            try
            {
                webSocket.Connect();

                await tcs.Task
                .ConfigureAwait(false);

                if (exception != null)
                {
                    throw exception;
                }
            }
            catch (OperationCanceledException) { }
            catch (Exception e)
            {
                if (!token.IsCancellationRequested)
                {
                    _logger?.LogError(e, $"{nameof(WebSocketSharpClient)}.{nameof(StreamAsync)}: WebSocket connect exception.");
                    throw;
                }
            }
            finally
            {
                if (webSocket.IsAlive)
                {
                    try { webSocket.Close(CloseStatusCode.Normal); }
                    catch (Exception e)
                    {
                        _logger?.LogError(e, $"{nameof(WebSocketSharpClient)}.{nameof(StreamAsync)}: WebSocket close exception.");
                    }
                }

                (webSocket as IDisposable)?.Dispose();

                if (IsStreaming)
                {
                    IsStreaming = false;
                    RaiseCloseEvent();
                }
            }
        }