Esempio n. 1
0
            public void Start(IPEndPoint remoteEndPoint)
            {
                if (Client != null)
                {
                    return;
                }
                Client = new Net.BlockingSocketClient();
                Client.Disconnected += (c, ep, e) =>
                {
                    Exception.Value = e;
                };
                Client.MessageReady += (c) =>
                {
                    lock (_lock)
                    {
                        if (c.MessageCount > 0)
                        {
                            var response = c?.GetNextMessage();
                            if (response == null)
                            {
                                System.Diagnostics.Debugger.Break();
                            }

                            var message = response.AsString();
                            if (message == Request.Value.ToUpper())
                            {
                                Responses.Value += 1;
                            }
                            else
                            {
                                Exception.Value = new System.Exception("Message Lost");
                            }
                        }
                        Mre.Set();
                    }
                };
                Client.ConnectAsync(remoteEndPoint).ContinueWith(task =>
                {
                    Mre.Reset();
                    _thread = W.Threading.Thread.Create(cts =>
                    {
                        while (!cts.IsCancellationRequested)
                        {
                            if (Client.IsConnected)
                            {
                                Request.Value   = string.Format("Message: {0}", Requests);
                                Requests.Value += 1;
                                Mre.Reset();
                                Client.Send(Request.Value.AsBytes());
                                Mre.Wait();
                            }
                            //W.Threading.Thread.Sleep(1);
                        }
                        if (Client.IsConnected)
                        {
                            Client.Disconnect();
                        }
                    });
                });
            }
Esempio n. 2
0
 /// <summary>
 /// Starts listening for clients
 /// </summary>
 /// <param name="ipAddress">The IP address to use</param>
 /// <param name="port">The port on which to listen</param>
 public void Start(IPAddress ipAddress, int port)
 {
     _server = new TcpListener(ipAddress, port);
     _server.Start();
     _listenProc = W.Threading.Thread.Create(ListenForClientsProc, ListenForClientsProc_OnComplete);
     IsListening = true;
 }
Esempio n. 3
0
 public Waiter(Client client, Client <Message> genericClient, int msTimeout)
 {
     _client = client;
     genericClient.MessageReceived += OnMessageReceived;
     //_cts = new CancellationTokenSource(msTimeout);
     _thread = W.Threading.Thread.Create(cts =>
     {
         bool isExpired = false;
         try
         {
             //cts is Cancelled before the response is sent
             while (!cts?.IsCancellationRequested ?? false)
             {
                 isExpired = DateTime.Now > Message.ExpireDateTime;
                 if (isExpired)
                 {
                     break;
                 }
                 System.Threading.Thread.Sleep(25);
             }
         }
         catch
         {
         }
         finally
         {
             if (isExpired)
             {
                 ExecuteCallback(null);
             }
         }
     }, null);//, _cts);
 }
Esempio n. 4
0
 /// <summary>
 /// Stops the server and frees resources
 /// </summary>
 public void Stop()
 {
     lock (_lockCleanup)
     {
         //ensure all clients are disconnected and disposed
         while (_clients.Count > 0)
         {
             try
             {
                 var client = _clients[0];
                 client.Dispose();
                 _clients.Remove(client);
             }
             finally
             {
             }
         }
     }
     _cts?.Cancel();
     _cts?.Dispose();
     _cts = null;
     _thread?.Cancel();
     _thread = null;
     Stopped?.Invoke(this);
 }
Esempio n. 5
0
 private void ThreadProc(CancellationTokenSource cts)
 {
     try
     {
         while (!cts.IsCancellationRequested)
         {
             if (!_sendQueue.IsEmpty && _stream != null)
             {
                 byte[] message;
                 if (_sendQueue.TryDequeue(out message))
                 {
                     TcpHelpers.SendMessageAsync(_stream, _sendBufferSize, message, exception =>
                     {
                         if (exception != null)
                         {
                             OnException?.Invoke(exception);
                         }
                         else
                         {
                             OnMessageSent?.Invoke();
                         }
                     }, cts).Wait();
                 }
             }
             System.Threading.Thread.Sleep(1);
         }
         cts?.Dispose();
     }
     catch (Exception e)
     {
         Log.e("MessageReader Thread Exception: {0}", e.Message);
     }
     _thread = null;
 }
Esempio n. 6
0
 //private Lockable<bool> IsDisposed { get; } = new Lockable<bool>();
 /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
 protected virtual void OnDispose()
 {
     _mreWriteComplete?.Dispose();
     _mreWriteComplete = null;
     _thread?.Dispose();
     _thread = null;
 }
Esempio n. 7
0
 private void ThreadProc(CancellationTokenSource cts)
 {
     try
     {
         while (!cts?.IsCancellationRequested ?? false)
         {
             if (!_sendQueue.IsEmpty && _stream != null)
             {
                 SocketData message;
                 if (_sendQueue.TryDequeue(out message))
                 {
                     Log.v("Writing Id=" + message.Id + ", Data Length=" + message.Data.Length);
                     StreamHelpers.SendMessageAsync(_stream, _sendBufferSize, message.Data, exception =>
                     {
                         if (exception != null)
                         {
                             OnException?.Invoke(exception);
                         }
                         else
                         {
                             OnMessageSent?.Invoke(message);
                         }
                     }, cts).Wait();
                 }
             }
             W.Threading.Thread.Sleep(1);
         }
         //cts?.Dispose();
     }
     catch (Exception e)
     {
         Log.e("MessageReader Thread Exception: {0}", e.Message);
     }
     _thread = null;
 }
Esempio n. 8
0
 /// <summary>
 /// Stops listening for and disconnects all current connections
 /// </summary>
 public void Stop()
 {
     while (_clients.Count > 0)
         _clients[0].Socket.Disconnect();
     _listenProc?.Cancel();
     _listenProc?.Join(1000);
     _listenProc = null;
     _server?.Stop();
     IsListening = false;
 }
Esempio n. 9
0
        /// <summary>
        /// Initialize the PipeTransceiver with the given PipeStream
        /// </summary>
        /// <param name="stream">The PipeStream to use</param>
        /// <param name="isServerSide">If True, this indicates a server-side client (primarily used for debugging purposes)</param>
        public void Initialize(PipeStream stream, bool isServerSide)
        {
            IsServerSide = isServerSide;
            Stream.Value = stream;

            //NetStandard doesn't support Read Timeouts, so we can't use that.
            //Our ReadMessageSize uses the Async method and CancellationTokenSource to force timeouts

            _thread = new Threading.Thread(ThreadProc);
        }
Esempio n. 10
0
 /// <summary>
 /// Stops listening for and disconnects all current connections
 /// </summary>
 public void Stop()
 {
     while (_clients.Count > 0)
     {
         _clients[0].DisconnectAsync().Wait();
     }
     _listenProc?.Cancel();
     _listenProc?.Join(1000);
     _listenProc = null;
     _server?.Stop();
     IsListening = false;
 }
Esempio n. 11
0
 public void Start(IPEndPoint ipEndPoint)
 {
     try
     {
         _server = new TcpListener(ipEndPoint.Address, ipEndPoint.Port);
         _server.Start();
         _listenProc = W.Threading.Thread.Create(ListenForClientsProc, ListenForClientsProc_OnComplete);
         IsListening = true;
     }
     catch (Exception e)
     {
         Log.e(e);
     }
 }
Esempio n. 12
0
 /// <summary>
 /// Starts listening for clients
 /// </summary>
 /// <param name="ipEndPoint">The IP address and port to use</param>
 public void Start(IPEndPoint ipEndPoint)
 {
     try
     {
         _server = new TcpListener(ipEndPoint.Address, ipEndPoint.Port);
         _server.Start();
         _listenProc = W.Threading.Thread.Create(ListenForClientsProc, ListenForClientsProc_OnComplete);
         IsListening = true;
     }
     catch (Exception e)
     {
         System.Diagnostics.Debugger.Break();
         System.Diagnostics.Debug.WriteLine(e.ToString());
     }
 }
Esempio n. 13
0
 public void Stop()
 {
     lock (_lock)
     {
         if (_thread != null)
         {
             Mre.Set();
             _thread.Cancel();
             _thread.WaitForValue(t => t.IsRunning == false, 1000);
             _thread.Dispose();
             _thread = null;
         }
         Client?.Disconnect();
         Client = null;
     }
 }
Esempio n. 14
0
        public MainWindowModel()
        {
            Title.Value = "Tungsten";

            //just demonstrate a background thread
            _thread = W.Threading.Thread.Create(cts =>
            {
                while (!cts.IsCancellationRequested)
                {
                    //technically, the value could change while we're looping and we'd never know (so mitigate this in production code)
                    if (RandomNumber.WaitForChanged()) //dont' block indefinitely
                    {
                        Count.Value += 1;
                    }
                }
            });
        }
Esempio n. 15
0
        /// <summary>
        /// Creates and starts a new thread
        /// </summary>
        /// <typeparam name="TParameterType">The Type of the item being extended</typeparam>
        /// <param name="this">The object to send into a new Thread</param>
        /// <param name="action">Action to call on a thread</param>
        /// <returns>A reference to the new W.Threading.Thread&lt;T&gt;</returns>
        public static W.Threading.Thread <TParameterType> CreateThread <TParameterType>(this TParameterType @this, Action <TParameterType, CancellationToken> action)
        {
            var thread = new W.Threading.Thread <TParameterType>(action, true);

            return(thread);
        }
Esempio n. 16
0
 /// <summary>
 /// Stops sending data (this may leave messages unsent)
 /// </summary>
 public void Stop()
 {
     _thread?.Cancel();
     _thread = null;
 }
Esempio n. 17
0
 /// <summary>
 /// Starts sending
 /// </summary>
 public void Start()
 {
     Stop();
     _thread = Threading.Thread.Create(ThreadProc);
 }
Esempio n. 18
0
        /// <summary>
        /// Creates the underlying NamedPipeClientStream and connects to the server
        /// </summary>
        public void Start(int maxConnections = -1, EPipeDirection direction = EPipeDirection.InOut)
        {
            Stop();
            _cts    = new CancellationTokenSource();
            _thread = W.Threading.Thread.Create(cts =>
            {
                Task.Run(() => { Task.Delay(100); Started?.Invoke(this); });
                while (!_cts?.IsCancellationRequested ?? false)
                {
                    NamedPipeServerStream stream = null;
                    try
                    {
                        stream = new NamedPipeServerStream(_name, (PipeDirection)direction, maxConnections, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
                        //Task.Run(() => { Started?.Invoke(this); });
                    }
                    catch (System.IO.IOException)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    catch (Exception e)
                    {
                        Exception?.Invoke(this, e);
                    }
                    try
                    {
                        //blocks until a client has connected
#if NETSTANDARD1_4
                        stream?.WaitForConnectionAsync(_cts.Token).ContinueWith(task => InitializeClient(stream, cts)).Wait(cts.Token);
#else
                        stream.WaitForConnection();
                        InitializeClient(stream, cts);
                        //var test = stream.BeginWaitForConnection(ar =>
                        //{
                        //    var s = (NamedPipeServerStream)ar.AsyncState;
                        //    s.EndWaitForConnection(ar);

                        //}, stream);
#endif
//                        {
//                            if (_cts?.IsCancellationRequested ?? true)
//                            {
//                                stream?.Dispose();
//                                return;
//                            }
//                            if (stream?.IsConnected ?? false)
//                            {
//                                //var p = (TClientType)Activator.CreateInstance(typeof(TClientType), stream);
//                                var client = (TClientType)Activator.CreateInstance(typeof(TClientType));
//                                client.Initialize(stream, true);
//                                client.Disconnected += (o, e) =>
//                                {
//                                    lock (_lockCleanup)
//                                    {
//                                        try
//                                        {
//                                            if (o != null && o is IPipeClient c)
//                                            {
//                                                c.Dispose();
//                                                _clients.Remove(c);
//                                            }
//                                        }
//                                        finally
//                                        {
//                                        }
//                                    }
//                                };
//                                _clients.Add(client);
//                                ClientConnected?.Invoke(client);
//                            }
//                        }
//#if NETSTANDARD1_4
//                        ).Wait(cts.Token);
//#endif
                    }
#if !NETSTANDARD1_4
                    catch (System.Threading.ThreadAbortException)
                    {
                        System.Threading.Thread.ResetAbort();
                    }
#endif
                    catch (System.IO.IOException e)
                    {
                        System.Diagnostics.Debugger.Break(); //why are we here?
                        Exception?.Invoke(this, e);
                    }
                    catch (System.Threading.Tasks.TaskCanceledException)
                    {
                        //ignore
                        System.Diagnostics.Debugger.Break(); //why are we here?
                        //Exception?.Invoke(this, e);
                    }
                    catch (System.OperationCanceledException) //happens when the server is closed
                    {
                        stream?.Dispose();                    //dispose the last allocated stream
                        //ignore
                        //Exception?.Invoke(this, e);
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debugger.Break(); //why are we here?
                        Exception?.Invoke(this, e);
                    }
                    System.Threading.Thread.Sleep(1); //play nice with other threads
                } //while
            });
        }
Esempio n. 19
0
        /// <summary>
        /// Creates a new thread
        /// </summary>
        /// <typeparam name="TParameterType">The Type of the item being extended</typeparam>
        /// <param name="this">The object to send into a new Thread</param>
        /// <param name="action">Action to call on a thread</param>
        /// <param name="autoStart">If True, the thread will immediately start running</param>
        /// <returns>A reference to the new W.Threading.Thread&lt;T&gt;</returns>
        public static W.Threading.Thread <TParameterType> CreateThread <TParameterType>(this object @this, Action <TParameterType, CancellationToken> action, bool autoStart)
        {
            var thread = new W.Threading.Thread <TParameterType>(action, autoStart);

            return(thread);
        }