public void CloseConnect(long handle) { if (Connects.ContainsKey(handle) == false) { return; } try { Connects[handle].Socket.Shutdown(SocketShutdown.Both); } // throws if client process has already closed catch (Exception) { } if (Connects.ContainsKey(handle) == false) { return; } Connects[handle].Socket.Close(); Connects[handle].ClientArgs.Dispose(); Connects.TryRemove(handle, out Link link); OnSocketClose?.Invoke(handle); //SocketAsyncEventArgs eventArgs = GetFreeEventArgs(); //eventArgs.UserToken = Connects[handle]; //Connects[handle].Socket.DisconnectAsync(eventArgs); }
/// <summary> /// Al ocurrir un error en la conexión socket /// </summary> /// <param name="e"></param> protected override void OnError(ErrorEventArgs e) { if (OnSocketClose == null) { return; } Debug.WriteLine(this, "Ocurrio un error en una conexión socket: " + e.Message, VerbosityLevel.Warning); SocketConnection socket = SelfSocketConnection(); OnSocketClose?.Invoke(this, socket); }
/// <summary> /// Al cerrarse la conexión socket /// </summary> /// <param name="e">Información del cierre</param> protected override void OnClose(CloseEventArgs e) { if (OnSocketClose == null) { return; } Debug.WriteLine(this, "Se desconecto correctamente una conexión socket: " + e.Reason, VerbosityLevel.Default); SocketConnection socket = SelfSocketConnection(); OnSocketClose?.Invoke(this, socket); }
/// <summary> /// Inicializar servidor socket en un puerto determinado /// </summary> /// <param name="port">Puerto a utilizar</param> public SocketServer(int port = 555) { var config = ConfigurationManager.Get <ISocketAdapterConfiguration>(); bool secure = Helper.SSL.Status == SSLCertificateStatus.Loaded && !config.OverrideSecure; m_webSocketServer = new WebSocketServer(port, secure); if (secure) { m_webSocketServer.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; m_webSocketServer.SslConfiguration.ServerCertificate = Helper.SSL.GlobalCertificate; Debug.WriteLine(this, "Inicializando SocketServer con SSL", VerbosityLevel.Info); } m_webSocketServer.AddWebSocketService("/", () => { var socketBehaviour = new SocketBehaviour(); socketBehaviour.OnSocketOpen += (s, e) => OnSocketOpen?.Invoke(this, e); socketBehaviour.OnSocketClose += (s, e) => OnSocketClose?.Invoke(this, e); return(socketBehaviour); }); m_webSocketServer.Start(); }
private void S_OnClose() { OnSocketClose?.Invoke(); }
public BluetoothDeviceConnection(TaskScheduler UITaskScheduler) : base(UITaskScheduler) { DeviceSelector = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort); _ConsoleBuffer = new StringBuilder(64); OnDeviceConnected += new TypedEventHandler <DeviceConnection, DeviceInformation>(async(connection, deviceInfo) => { if (IsDeviceConnected) { // Create a standard networking socket and connect to the target _socket = new StreamSocket(); _connectAction = _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); try { await _connectAction.AsTask().ContinueWith(async(task) => { if (task.Status != TaskStatus.RanToCompletion) { CloseDevice(); return; } _writer = new DataWriter(_socket.OutputStream); _writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; _reader = new DataReader(_socket.InputStream); _reader.InputStreamOptions = InputStreamOptions.Partial; _reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; // String builder storing the last received JSON string. StringBuilder _JSONRawData = new StringBuilder(); _isSocketConnected = true; OnSocketConnected?.Invoke(this, deviceInfo); // Receiving loop while (_reader != null) { uint size; if (_isJSONCommunicationStarted) { size = await _reader.LoadAsync(512); } else { size = await _reader.LoadAsync(sizeof(byte)); } if (size < sizeof(byte)) { // The underlying socket was closed before we were able to read the whole data CloseDevice(); break; } while (_reader.UnconsumedBufferLength > 0) { var c = (char)_reader.ReadByte(); if (_isJSONCommunicationStarted) { if (c == '\n') { try { var DeserializedData = JsonConvert.DeserializeObject <JSONDataSource>(_JSONRawData.ToString(), new JsonDataSourceConverter(), new BoolConverter()); if (DeserializedData != null) { OnJSONObjectReceived?.Invoke(this, DeserializedData); } } catch (Newtonsoft.Json.JsonReaderException) { } finally { _JSONRawData.Clear(); } } else { _JSONRawData.Append(c); } } else { // TODO: correct bug: "start" don't append in _ConsoleBuffer (add a boolean 'FirstJSONObjReceived' ?) // If the received data isn't JSON objects, add it to _ConsoleBuffer _ConsoleBuffer.Append(c); } } // Notify buffer changed if (!_isJSONCommunicationStarted) { ConsoleBufferChanged?.Invoke(this, null); } } }, UITaskScheduler); } catch (TaskCanceledException) { CloseDevice(); } } }); OnDeviceClose += new TypedEventHandler <DeviceConnection, DeviceInformation>((connection, deviceInfo) => { if (_connectAction?.Status == AsyncStatus.Started) { _connectAction?.Cancel(); } _connectAction = null; _reader?.Dispose(); _reader = null; _writer?.Dispose(); _writer = null; _isSocketConnected = false; _socket?.Dispose(); _socket = null; OnSocketClose?.Invoke(this, deviceInfo); _isJSONCommunicationStarted = false; _connectAction = null; }); }
/// <summary> /// Event handler for closing a socket /// </summary> private void Transport_OnSocketClose(string mess) { OnSocketClose?.Invoke(mess); }
/// <summary> /// Event handler for closing a socket /// </summary> private void Socket_OnClose(object sender, CloseEventArgs e) { logger.Trace("{0}", JsonConvert.SerializeObject(e)); OnSocketClose?.Invoke(e.Reason); }