internal void Update() { EventArgs e; while (eventQueue.Count > 0) { lock (eventQueueLock) { e = eventQueue.Dequeue(); } if (e is CloseEventArgs) { OnClose?.Invoke(this, e as CloseEventArgs); WebSocketManager.Instance.Remove(this); } else if (e is OpenEventArgs) { OnOpen?.Invoke(this, e as OpenEventArgs); } else if (e is MessageEventArgs) { OnMessage?.Invoke(this, e as MessageEventArgs); } else if (e is ErrorEventArgs) { OnError?.Invoke(this, e as ErrorEventArgs); } } }
private void OnConnected(IAsyncResult ar) { if (m_socket == null) { return; } Socket client = (Socket)ar.AsyncState; ar.AsyncWaitHandle.Close(); try { lock (m_sync_lock) { client.EndConnect(ar); this.BeginReceive(); if (OnOpen != null) { OnOpen.Invoke(0); } } } catch (Exception e) { Log.Error("连接失败:" + e.Message); this.Close(); } }
internal void Update() { while (eventArgsQueue.Count > 0) { EventArgs e; lock (eventArgsQueue) { e = eventArgsQueue.Dequeue(); } if (e is CloseEventArgs && OnClose != null) { OnClose.Invoke(this, e as CloseEventArgs); } else if (e is OpenEventArgs && OnOpen != null) { OnOpen.Invoke(this, e as OpenEventArgs); } else if (e is MessageEventArgs && OnMessage != null) { OnMessage.Invoke(this, e as MessageEventArgs); } else if (e is ErrorEventArgs && OnError != null) { OnError.Invoke(this, e as ErrorEventArgs); } } }
public void Connect(IPEndPoint serverIPEP, ushort bufferSize = 8 * 1024) // 8KB { _Cleanup(); if (bufferSize < 64) { throw new ArgumentOutOfRangeException(nameof(bufferSize)); } ServerIPEP = serverIPEP ?? throw new ArgumentNullException(nameof(serverIPEP)); BufferSize = bufferSize; _isOpen = new ValueWrapper <bool>(true); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.ReceiveBufferSize = bufferSize; _socket.SendBufferSize = bufferSize; _socket.Bind(new IPEndPoint(IPAddress.Any, 0)); _thread = new Thread(_ReceiveThread); _thread.Start(); LocalIPEP = (IPEndPoint)_socket.LocalEndPoint; OnOpen?.Invoke(); }
public void SetVisibility(bool visible) { var currentRenderProfile = DCL.RenderProfileManifest.i.currentProfile; if (!visible && view.isOpen) { currentRenderProfile.avatarProfile.currentProfile = currentRenderProfile.avatarProfile.inWorld; currentRenderProfile.avatarProfile.Apply(); if (prevMouseLockState) { Utils.LockCursor(); } OnClose?.Invoke(); } else if (visible && !view.isOpen) { currentRenderProfile.avatarProfile.currentProfile = currentRenderProfile.avatarProfile.avatarEditor; currentRenderProfile.avatarProfile.Apply(); prevMouseLockState = Utils.isCursorLocked; Utils.UnlockCursor(); OnOpen?.Invoke(); } currentRenderProfile.avatarProfile.Apply(); view.SetVisibility(visible); }
private async Task StartHandshakeWithServer() { var httpEOF = Encoding.UTF8.GetBytes("\r\n\r\n"); var received = new List <byte>(); var buffer = new byte[2048]; var host = uri.Host; var path = uri.PathAndQuery; var eol = "\r\n"; var handshake = "GET " + path + " HTTP/1.1" + eol; handshake += "Host: " + host + eol; handshake += "Upgrade: websocket" + eol; handshake += "Connection: Upgrade" + eol; handshake += "Sec-WebSocket-Key: V2ViU29ja2V0Q2xpZW50" + eol; handshake += "Sec-WebSocket-Version: 13" + eol; handshake += eol; var handshakeBytes = Encoding.UTF8.GetBytes(handshake); await stream.WriteAsync(handshakeBytes, 0, handshakeBytes.Length); while (received.IndexOf(httpEOF) == -1) { var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); received.AddRange(buffer.Take(bytesRead)); } OnOpen.Invoke(this, null); var doNotWait = StartReceivingFromServer(); }
/// <summary> /// Emit the open connector event. /// </summary> protected virtual void EmitOpen() { OnOpen?.Invoke(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Flush(); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed }
public override void ParseData(string command) { var jObject = JObject.Parse(command); if (jObject.ParseString("status", out string status)) { if (status == "open") { Status = status; OnOpen?.Invoke(this, EventArgs.Empty); } else if (status == "close") { Status = status; OnClose?.Invoke(this, EventArgs.Empty); } } if (jObject.ParseInt("no_close", out int noClose)) { if (noClose == 60) { NotClosedFor1Minute?.Invoke(this, EventArgs.Empty); } else if (noClose == 300) { NotClosedFor5Minutes?.Invoke(this, EventArgs.Empty); } } Voltage = jObject.ParseVoltage(); }
public override void WriteXml(ref XmlElement parent) { //Create a new Tag node. XmlElement tagElement = parent.OwnerDocument.CreateElement("Tag"); tagElement.SetAttribute("Name", Name); tagElement.SetAttribute("Description", Description); tagElement.SetAttribute("DataType", DataType.ToString()); tagElement.SetAttribute("Address", Address); tagElement.SetAttribute("Driver", Driver.Id); tagElement.SetAttribute("Dsn", Dsn); tagElement.SetAttribute("SqlCommand", SqlCommand); tagElement.SetAttribute("OnChange", OnChange.ToString()); tagElement.SetAttribute("OnOpen", OnOpen.ToString()); tagElement.SetAttribute("OnClose", OnClose.ToString()); foreach (DataRow param in _sqlParams.Rows) { XmlElement paramElement = parent.OwnerDocument.CreateElement("SqlParam"); paramElement.SetAttribute("Name", param["Name"].ToString()); paramElement.SetAttribute("Value", param["Value"].ToString()); tagElement.AppendChild(paramElement); } parent.AppendChild(tagElement); }
public async void OpenWebsocket(string url, List <KeyValuePair <string, string> > websocketheaders) { socket = new MessageWebSocket(); socket.Closed += (sender, args) => { Debug.Log("Stopped reason: " + args.Reason); }; socket.MessageReceived += OnWebSocketMessage; socket.Control.MessageType = SocketMessageType.Utf8; socket.ServerCustomValidationRequested += OnServerCustomValidationRequested; socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); foreach (var header in websocketheaders) { socket.SetRequestHeader(header.Key, header.Value); } await socket.ConnectAsync(new Uri(url)); messageWriter = new DataWriter(socket.OutputStream); if (OnOpen != null) { OnOpen.Invoke(); } }
private void RaiseOpen() { if (OnOpen != null) { OnOpen.Invoke(this, new EventArgs()); } }
/// <summary> /// Informa a abertura do WebSocket /// </summary> internal virtual void SendOnOpen() { new Thread(() => { OnOpen?.Invoke(this); }).Start(); }
public void SetVisibility(bool visible) { var currentRenderProfile = DCL.RenderProfileManifest.i.currentProfile; if (!visible && view.isOpen) { DCL.Environment.i.messaging.manager.paused = false; currentRenderProfile.avatarProfile.currentProfile = currentRenderProfile.avatarProfile.inWorld; currentRenderProfile.avatarProfile.Apply(); if (prevMouseLockState) { Utils.LockCursor(); } OnClose?.Invoke(); } else if (visible && !view.isOpen) { DCL.Environment.i.messaging.manager.paused = DataStore.i.isSignUpFlow.Get(); currentRenderProfile.avatarProfile.currentProfile = currentRenderProfile.avatarProfile.avatarEditor; currentRenderProfile.avatarProfile.Apply(); prevMouseLockState = Utils.isCursorLocked; Utils.UnlockCursor(); OnOpen?.Invoke(); } currentRenderProfile.avatarProfile.Apply(); view.SetVisibility(visible); }
public IEnumerator Connect() { m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString()); m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData); m_Socket.OnOpen += (sender, e) => { if (OnOpen != null) { OnOpen.Invoke(sender, e); } m_IsConnected = true; }; m_Socket.OnClose += (sender, e) => { if (OnClose != null) { OnClose.Invoke(sender, e); } }; m_Socket.OnError += (sender, e) => m_Error = e.Message; m_Socket.ConnectAsync(); while (!m_IsConnected && m_Error == null) { yield return(0); } }
internal void DispatchEvent(PopupEventArgs eventArgs) { switch (eventArgs.Type) { case "close": OnClose?.Invoke(eventArgs); break; case "drag": OnDrag?.Invoke(eventArgs); break; case "dragend": OnDragEnd?.Invoke(eventArgs); break; case "dragstart": OnDragStart?.Invoke(eventArgs); break; case "open": OnOpen?.Invoke(eventArgs); break; } }
public void Open(string path, bool autoPlay) { player.source = VideoSource.Url; player.url = path; player.Prepare(); void OnPrepared(VideoPlayer player) { OnReady?.Invoke(); if (autoPlay) { Play(); } } void OnErrorReceived(VideoPlayer player, string message) { OnError?.Invoke(new Exception(message)); } player.prepareCompleted -= OnPrepared; player.prepareCompleted += OnPrepared; player.errorReceived -= OnErrorReceived; player.errorReceived += OnErrorReceived; OnOpen?.Invoke(path); }
private async Task ConnectAsync() { var tcs = new TaskCompletionSource <bool>(); _socket.OnClose += (sender, args) => { if (!args.WasClean) { if (_attempts == 60) { tcs.TrySetException(new SocketNotConnectedException()); } Thread.Sleep(TimeSpan.FromSeconds(1)); _socket.Connect(); _attempts++; } OnClose?.Invoke(); }; _socket.OnOpen += (sender, args) => { tcs.TrySetResult(true); OnOpen?.Invoke(); }; _socket.ConnectAsync(); await tcs.Task.ConfigureAwait(false); }
public override async Task OpenAsync() { State = ChannelState.Connecting; client = new UdpClient(Port); client.DontFragment = true; try { if (!String.IsNullOrEmpty(hostname)) { client.Connect(hostname, port); } else { client.Connect(remoteEP); } State = ChannelState.Open; OnOpen?.Invoke(this, new ChannelOpenEventArgs(Id, null)); } catch (Exception ex) { client = null; Trace.TraceError("UDP client channel {0} open error {1}", Id, ex.Message); OnError?.Invoke(this, new ChannelErrorEventArgs(Id, ex)); } await Task.CompletedTask; }
private static IWebsocket CreateSocket() { bool open = false; bool closed = true; IWebsocket obj = Mock.Of <IWebsocket>(); var socket = Mock.Get(obj); socket.Setup(s => s.Close()).Returns(Task.FromResult(true)).Callback(() => { var closing = socket.Object.IsOpen; open = false; closed = true; if (closing) { socket.Raise(s => s.OnClose += null); } OnClose?.Invoke(socket); }); socket.Setup(s => s.IsOpen).Returns(() => open); socket.Setup(s => s.Send(It.IsAny <string>())).Callback(new Action <string>((data) => { OnSend?.Invoke(socket, data); })); socket.Setup(s => s.IsClosed).Returns(() => closed); socket.Setup(s => s.Connect()).Returns(Task.FromResult(true)).Callback(() => { socket.Setup(s => s.IsOpen).Returns(() => open); socket.Setup(s => s.IsClosed).Returns(() => closed); open = true; closed = false; socket.Raise(s => s.OnOpen += null); OnOpen?.Invoke(socket); }); return(socket.Object); }
public async Task Connect() { try { Log.Debug("Connecting to " + url); if (ws != null && (ws.State == WebSocketState.Aborted || ws.State == WebSocketState.Closed)) { ws.Dispose(); ws = null; ws = new ClientWebSocket(); src = new CancellationTokenSource(); } if (ws == null) { ws = new ClientWebSocket(); src = new CancellationTokenSource(); } if (ws.State == WebSocketState.Connecting || ws.State == WebSocketState.Open) { return; } await ws.ConnectAsync(new Uri(url), src.Token); Log.Information("Connected to " + url); Task receiveTask = Task.Run(async() => await receiveLoop(), src.Token); Task pingTask = Task.Run(async() => await PingLoop(), src.Token); OnOpen?.Invoke(); } catch (Exception ex) { Log.Error(ex, ""); OnClose?.Invoke(ex.Message); } }
private void HandleOnOpen(object sender, EventArgs e) { if (OnOpen != null) { OnOpen.Invoke(sender, e); } }
public void SetVisibility(bool visible) { if (view == null) { return; } if (visible && !view.IsActive()) { Utils.UnlockCursor(); view.RefreshData(); OnOpen?.Invoke(); } else if (!visible && view.IsActive()) { OnClose?.Invoke(); } view.SetVisibility(visible); if (visible) { AudioScriptableObjects.dialogOpen.Play(true); AudioScriptableObjects.listItemAppear.ResetPitch(); } else { AudioScriptableObjects.dialogClose.Play(true); } }
public async Task Connect() { try { m_TokenSource = new CancellationTokenSource(); m_CancellationToken = m_TokenSource.Token; m_Socket = new ClientWebSocket(); foreach (var header in headers) { m_Socket.Options.SetRequestHeader(header.Key, header.Value); } foreach (string subprotocol in subprotocols) { m_Socket.Options.AddSubProtocol(subprotocol); } await m_Socket.ConnectAsync(uri, m_CancellationToken); await new WaitForUpdate(); if (!m_CancellationToken.IsCancellationRequested) { OnOpen?.Invoke(); _ = Receive(); } } catch (Exception ex) { Debug.Log("received connection error"); OnError?.Invoke(ex.Message); OnClose?.Invoke(WebSocketCloseCode.Abnormal); } }
public TrayIcon() { _ni = new NotifyIcon(); _ni.Visible = true; _ni.Icon = PreventShutDownHelper.Prevent ? GetIcon(IconGreenName) : GetIcon(IconRedName); _ni.BalloonTipTitle = "Shut down"; _ni.BalloonTipText = "Shut down is in progress"; _ni.Text = "Shut Down"; SetContextMenu(false); _isShutDownInProgress = false; _ni.DoubleClick += (s, e) => { OnOpen?.Invoke(); }; _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) }; _timer.Tick += (s, e) => { OnTimerTick(); }; _timer.Start(); }
internal void HandleOnOpen() { if (OnOpen != null) { OnOpen.Invoke(this, new OpenEventArgs()); } }
private void OnOpenReceived() { coroutineRunner.Run(() => { OnOpen?.Invoke(); }); }
public override void ParseData(string command) { var jObject = JObject.Parse(command); if (jObject["status"] != null) { Status = jObject["status"].ToString(); if (Status == "open") { OnOpen?.Invoke(this, EventArgs.Empty); } else if (Status == "close") { OnClose?.Invoke(this, EventArgs.Empty); } } if (jObject["voltage"] != null && float.TryParse(jObject["voltage"].ToString(), out float v)) { Voltage = v / 1000; } Debug.WriteLine($"Sid: {Sid}, Type: {GetType().Name}, Command: {command}, Sensor: {this}"); }
public async Task ConnectAsync() { if (dispose) { return; } if (socket?.State == WebSocketState.Open || socket?.State == WebSocketState.Connecting) { throw new Exception("WebSocket is already open/connecting."); } socket = new ClientWebSocket(); if (Headers != null) { foreach (var kv in Headers) { socket.Options.SetRequestHeader(kv.Key, kv.Value); } } await socket.ConnectAsync(Endpoint, socketTokenSource.Token); Task.Run(() => Listen()); OnOpen.InvokeAsync(); }
public IEnumerator Connect() { m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString()); m_Socket.OnMessage += (sender, e) => { m_Messages.Enqueue(e.RawData); }; m_Socket.OnOpen += (sender, e) => { m_IsConnected = true; isConnected = true; }; m_Socket.OnError += (sender, e) => { m_Error = e.Message; if (OnError != null) { OnError.Invoke(this, new ErrorEventArgs(m_Error)); } }; m_Socket.ConnectAsync(); while (!m_IsConnected && m_Error == null) { yield return(0); } if (OnOpen != null) { OnOpen.Invoke(this, new EventArgs()); } }
public void Working(ReceiveEventHandler receive = null) { FleckLog.Level = LogLevel.Debug; allSockets = new List <IWebSocketConnection>(); server = new WebSocketServer("ws://0.0.0.0:7066"); server.RestartAfterListenError = true; server.Start(socket => { socket.OnOpen = () => { allSockets.Add(socket); OnOpen?.BeginInvoke(socket, null, null); }; socket.OnClose = () => { allSockets.Remove(socket); OnClose?.BeginInvoke(socket, null, null);//通知断开 }; socket.OnMessage = message => { receive?.BeginInvoke(message, socket, null, null); }; socket.OnError = ex => { OnError?.BeginInvoke(ex, socket, null, null); }; }); }