///<summary> /// Starts the asynchronous connection process. /// User callbacks are: OnConnected() when successful - or OnDisconnect() in case of failure. /// UserContext.Data will contain the data object passed here. /// Timeout is defined by the TCP stack. ///</summary> public void BeginConnect(object data) { if (_client != null) { return; } _context = new Context(null, null); _context.BufferSize = 512; _context.UserContext.DataFrame = new DataFrame(); _context.UserContext.SetOnConnect(OnConnect); _context.UserContext.SetOnConnected(OnConnected); _context.UserContext.SetOnDisconnect(OnDisconnect); _context.UserContext.SetOnSend(OnSend); _context.UserContext.SetOnReceive(OnReceive); _context.UserContext.Data = data; try { ReadyState = ReadyStates.CONNECTING; _context.UserContext.OnConnect(); _client = new TcpClient(); _context.Connection = _client; _connecting = true; _client.BeginConnect(_host, _port, OnClientConnected, null); } catch (Exception ex) { Disconnect(); _context.UserContext.LatestException = ex; _context.UserContext.OnDisconnect(); } }
public void Connect() { if (_client != null) return; try { ReadyState = ReadyStates.CONNECTING; _client = new TcpClient(); _connecting = true; _client.BeginConnect(_host, _port, OnRunClient, null); var waiting = new TimeSpan(); while (_connecting && waiting < ConnectTimeout) { var timeSpan = new TimeSpan(0, 0, 0, 0, 100); waiting = waiting.Add(timeSpan); Thread.Sleep(timeSpan.Milliseconds); } if (_connecting) throw new Exception("Timeout"); } catch (Exception) { Disconnect(); OnFailedConnection(null); } }
public void Disconnect() { _connecting = false; if (_client == null) { return; } var dataFrame = new DataFrame(); dataFrame.Append(new byte[0]); var bytes = dataFrame.AsFrame()[0].Array; ReadyState = ReadyStates.CLOSING; bytes[0] = 0x88; if (_context != null && _context.UserContext != null) { _context.UserContext.Send(bytes); } _client.Close(); _client = null; ReadyState = ReadyStates.CLOSED; }
public void Connect() { if (_client != null) { return; } try { ReadyState = ReadyStates.CONNECTING; _client = new TcpClient(); _connecting = true; _client.BeginConnect(_host, _port, OnRunClient, null); var waiting = new TimeSpan(); while (_connecting && waiting < ConnectTimeout) { var timeSpan = new TimeSpan(0, 0, 0, 0, 100); waiting = waiting.Add(timeSpan); Thread.Sleep(timeSpan.Milliseconds); } } catch (Exception) { Disconnect(); } }
public void Send(string body) { if (client == null || requestMessage == null) { return; } if (requestTask != null) { return; } requestTask = Task.Run(async() => { try { var responseHeaders = await client.SendRequestAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead); ProjectRuntime.Inst.DispatchRuntimeCode(() => { objRef.SetProperty(JavaScriptPropertyId.FromString("status"), JavaScriptValue.FromInt32((int)responseHeaders.StatusCode), true); string statusText = $"{(int)responseHeaders.StatusCode} {responseHeaders.ReasonPhrase}"; objRef.SetProperty(JavaScriptPropertyId.FromString("statusText"), JavaScriptValue.FromString(statusText), true); }); ReadyState = ReadyStates.Headers_Received; // ReadyState = ReadyStates.Loading; // ignore, we don't do partial responses var content = await responseHeaders.Content.ReadAsStringAsync(); ProjectRuntime.Inst.DispatchRuntimeCode(() => { objRef.SetProperty(JavaScriptPropertyId.FromString("responseType"), JavaScriptValue.FromString("text"), true); objRef.SetProperty(JavaScriptPropertyId.FromString("response"), JavaScriptValue.FromString(content), true); objRef.SetProperty(JavaScriptPropertyId.FromString("responseText"), JavaScriptValue.FromString(content), true); var callback = objRef.Get("onload"); if (callback.ValueType == JavaScriptValueType.Function) { callback.CallFunction(callback); } }); } catch (Exception e) { ProjectRuntime.Inst.DispatchRuntimeCode(() => { var callback = objRef.Get("onerror"); if (callback.ValueType == JavaScriptValueType.Function) { callback.CallFunction(callback); } }); } ReadyState = ReadyStates.Done; requestMessage = null; requestTask = null; }); /* * cancellationTokenSource = new CancellationTokenSource(); * requestTask = Task.Run(async () => { * var response = await request;//.AsTask(cancellationTokenSource.Token); * //response. * int dsa = 0; * }); */ }
public void Open(string method, string url) { var httpMethod = GetHttpMethod(method); if (httpMethod == null) { return; } client = new HttpClient(); try { requestMessage = new HttpRequestMessage(httpMethod, new Uri(url)); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); return; } ReadyState = ReadyStates.Opened; }
public void Disconnect() { _connecting = false; if (_client == null) { return; } if (_context != null) { if (ReadyState == ReadyStates.OPEN) { ReadyState = ReadyStates.CLOSING; // see http://stackoverflow.com/questions/17176827/websocket-close-packet var bytes = new byte[6]; bytes[0] = 0x88; // Fin + Close bytes[1] = 0x80; // Mask = 1, Len = 0 bytes[2] = 0; bytes[3] = 0; bytes[4] = 0; // Mask = 0 bytes[5] = 0; // Mask = 0 _context.UserContext.Send(bytes, raw: true); Thread.Sleep(30); // let the send thread do its work } ReadyState = ReadyStates.CLOSING; _context.Dispose(); // sets Connected=false and notifies UserContext } if (_client != null) { var temp = _client; _client = null; temp.Close(); } IsAuthenticated = false; ReadyState = ReadyStates.CLOSED; }
private bool CheckAuthenticationResponse(Context context) { var receivedData = context.UserContext.DataFrame.ToString(); var header = new Header(receivedData); var handshake = new ServerHandshake(header); if (Authentication.GenerateAccept(_handshake.Key) != handshake.Accept) { return(false); } if (SubProtocols != null) { if (header.SubProtocols == null) { return(false); } foreach (var s in SubProtocols) { if (header.SubProtocols.Contains(s) && String.IsNullOrEmpty(CurrentProtocol)) { CurrentProtocol = s; } } if (String.IsNullOrEmpty(CurrentProtocol)) { return(false); } } ReadyState = ReadyStates.OPEN; IsAuthenticated = true; _connecting = false; context.UserContext.OnConnected(); return(true); }
private bool CheckAuthenticationResponse(Context context) { var receivedData = context.UserContext.DataFrame.ToString(); var header = new Header(receivedData); var handshake = new ServerHandshake(header); if (Authentication.GenerateAccept(_handshake.Key) != handshake.Accept) return false; if (SubProtocols != null) { if (header.SubProtocols == null) { return false; } foreach (var s in SubProtocols) { if (header.SubProtocols.Contains(s) && String.IsNullOrEmpty(CurrentProtocol)) { CurrentProtocol = s; } } if(String.IsNullOrEmpty(CurrentProtocol)) { return false; } } ReadyState = ReadyStates.OPEN; IsAuthenticated = true; _connecting = false; context.UserContext.OnConnected(); return true; }
public void Disconnect() { _connecting = false; if (_client == null) return; var dataFrame = new DataFrame(); dataFrame.Append(new byte[0]); var bytes = dataFrame.AsFrame()[0].Array; ReadyState = ReadyStates.CLOSING; bytes[0] = 0x88; _context.UserContext.Send(bytes); _client.Close(); _client = null; ReadyState = ReadyStates.CLOSED; }
///<summary> /// Starts the asynchronous connection process. /// User callbacks are: OnConnected() when successful - or OnDisconnect() in case of failure. /// UserContext.Data will contain the data object passed here. /// Timeout is defined by the TCP stack. ///</summary> public void BeginConnect(object data) { if (_client != null) return; _context = new Context(null, null); _context.BufferSize = 512; _context.UserContext.DataFrame = new DataFrame(); _context.UserContext.SetOnConnect(OnConnect); _context.UserContext.SetOnConnected(OnConnected); _context.UserContext.SetOnDisconnect(OnDisconnect); _context.UserContext.SetOnSend(OnSend); _context.UserContext.SetOnReceive(OnReceive); _context.UserContext.Data = data; try { ReadyState = ReadyStates.CONNECTING; _context.UserContext.OnConnect(); _client = new TcpClient(); _context.Connection = _client; _connecting = true; _client.BeginConnect(_host, _port, OnClientConnected, null); } catch (Exception ex) { Disconnect(); _context.UserContext.LatestException = ex; _context.UserContext.OnDisconnect(); } }
public void Disconnect() { _connecting = false; if (_client == null) return; if (_context != null) { if (ReadyState == ReadyStates.OPEN) { ReadyState = ReadyStates.CLOSING; // see http://stackoverflow.com/questions/17176827/websocket-close-packet var bytes = new byte[6]; bytes[0] = 0x88; // Fin + Close bytes[1] = 0x80; // Mask = 1, Len = 0 bytes[2] = 0; bytes[3] = 0; bytes[4] = 0; // Mask = 0 bytes[5] = 0; // Mask = 0 _context.UserContext.Send(bytes, raw: true); Thread.Sleep(30); // let the send thread do its work } _context.Connected = false; ReadyState = ReadyStates.CLOSING; _context.Cancellation.Cancel(); _context.Connection = null; } _client.Close(); _client = null; IsAuthenticated = false; ReadyState = ReadyStates.CLOSED; }
private void CheckAuthenticationResponse(Context context) { var receivedData = context.UserContext.DataFrame.ToString(); var header = new Header(receivedData); var handshake = new ServerHandshake(header); if (Authentication.GenerateAccept(_handshake.Key) != handshake.Accept) return; ReadyState = ReadyStates.OPEN; IsAuthenticated = true; _connecting = false; context.UserContext.OnConnected(); }