Ejemplo n.º 1
0
 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);
 }
Ejemplo n.º 2
0
            /// <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);
            }
Ejemplo n.º 3
0
            /// <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);
            }
Ejemplo n.º 4
0
        /// <summary>
        /// Start the thread for elaborate the images and sending it
        /// </summary>
        /// <param name="callbackOnError">function to call on error</param>
        /// <param name="callbackSocketClose">function to call when socket is close</param>
        private void StartThreads(OnFrameSendingError callbackOnError, OnSocketClose callbackSocketClose)
        {
            endElaboration = false;
            requests       = new ConcurrentQueue <FrameNode>();
            Debug.Log("Parameter set");
            encodingThread = new Thread(JpegEncoding);
            encodingThread.Start();
            sendingThread = new Thread(ImageSending);
            sendingThread.Start();

            this.callbackOnFrameSendingError = callbackOnError;
            this.callbackOnClose             = callbackSocketClose;
            Debug.Log("Thread start");
        }
Ejemplo n.º 5
0
        /// <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();
        }
Ejemplo n.º 6
0
 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;
            });
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Event handler for closing a socket
 /// </summary>
 private void Transport_OnSocketClose(string mess)
 {
     OnSocketClose?.Invoke(mess);
 }
Ejemplo n.º 9
0
        /// <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);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Start the connection and if success the threads to elaborate and send the frames
        /// </summary>
        /// <param name="serverIpAddress">IP address</param>
        /// <param name="serverPort">Elaboration Server Port</param>
        /// <param name="phoneId">A UUID of the phone that make the connection</param>
        /// <param name="callbackOnError">function to call on error</param>
        /// <param name="callbackSocketClose">function to call when socket is close</param>
        /// <returns>true if the connection success, else false</returns>
        private bool startSocket(string serverIpAddress, uint serverPort, string phoneId, OnFrameSendingError callbackOnError, OnSocketClose callbackSocketClose)
        {
            bool result = createConnection(connectionId, serverIpAddress, serverPort, phoneId);

            if (result == false)
            {
                return(false);
            }
            active = true;
            Debug.Log("Image Sending init correctly");
            StartThreads(callbackOnError, callbackSocketClose);
            return(true);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Set the session ID of the session that client need to join
 /// </summary>
 /// <param name="position">the socket ID</param>
 /// <param name="streamId">the ID of the stream</param>
 public bool InitConnectionAsClient(string serverIpAddress, uint serverPort, string phoneId, ulong maximumRate, string streamId, OnFrameSendingError callbackOnError, OnSocketClose callbackSocketClose)
 {
     initLibrary(maximumRate);
     setSessionIdentifier(connectionId, streamId);
     return(startSocket(serverIpAddress, serverPort, phoneId, callbackOnError, callbackSocketClose));
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Init a connection to the server
        /// </summary>
        /// <param name="serverIpAddress">IP address</param>
        /// <param name="serverPort">Elaboration Server Port</param>
        /// <param name="phoneId">A UUID of the phone that make the connection</param>
        /// <param name="maximumRate">the maximum usable bandwidth by the socket</param>
        /// <param name="numberOfClients">number of clients for the session</param>
        /// <param name="callbackOnError">function to call on error</param>
        /// <param name="callbackSocketClose">function to call when socket is close</param>
        /// <returns>the UUID of the session created</returns>
        public string InitConnectionAsHost(string serverIpAddress, uint serverPort, string phoneId, ulong maximumRate, uint numberOfClients, OnFrameSendingError callbackOnError, OnSocketClose callbackSocketClose)
        {
            initLibrary(maximumRate);

            setSessionClient(connectionId, numberOfClients);
            if (startSocket(serverIpAddress, serverPort, phoneId, callbackOnError, callbackSocketClose))
            {
                return(getStreamId(connectionId));
            }
            return("");
        }