Esempio n. 1
0
        public List <string> Read(string terminators = "\r\n\0")
        {
            logger.Debug($"Read start");
            using (semaphore.UseOnce())
            {
                logger.Debug($"Read acquired semaphore");
                int read;
                try
                {
                    using (TimeoutAction.Set(timeout, () => { Close(); logger.Debug($"Read timeout expired"); }))
                        read = socket.Receive(parser.Buffer, parser.Offset, parser.BufferLength, SocketFlags.None);
                    logger.Debug($"Read completed");
                }
                catch (Exception ex)
                {
                    logger.Warn(ex);
                    Close();
                    throw new ConnectionLostException("Socket error", ex);
                }

                if (read == 0)
                {
                    logger.Warn("Read recv returned zero bytes");
                    Close();
                    throw new ConnectionLostException("Recv returned zero bytes");
                }

                return(parser.Parse(read, terminators).ToList());
            }
        }
Esempio n. 2
0
        public void Should_execute_after_timeout()
        {
            var sw = Stopwatch.StartNew();

            using (TimeoutAction.Set(100, () => sw.Stop()))
                Thread.Sleep(2000);
            sw.ElapsedMilliseconds.Should().BeInRange(0, 150);
        }
Esempio n. 3
0
 protected virtual Task Connect(string host, int port, int timeout = DefaultConnectTimeout)
 {
     Logger.Information("Connect with {host}:{port} timeout {timeout}", host, port, timeout);
     ThrowIfNotReady();
     return(Task.Run(() =>
     {
         Logger.Debug("Connect task started");
         using (sendReceiveSemaphore.UseOnce())
         {
             Logger.Debug("Connect task acquired semaphore");
             var client = new Socket(SocketType.Stream, ProtocolType.Tcp);
             using (TimeoutAction.Set(timeout, () => { client.CloseForce(); Logger.Debug("Timeout expired"); }))
                 client.ConnectAsync(host, port).Wait(timeout + 100);
             Logger.Debug("Connect task socket connected");
             stream = new ByteStream(client, receiveTimeout);
             Logger.Debug("Connect task completed");
         }
     }));
 }
Esempio n. 4
0
 public void Send(string data)
 {
     try
     {
         logger.Debug($"Send {data}");
         semaphore.Wait();
         logger.Debug($"Send acquired semaphore");
         using (TimeoutAction.Set(timeout, () => { Close(); logger.Debug($"Send timeout expired"); }))
             socket.Send(Encoding.ASCII.GetBytes(data));
         logger.Debug($"Send completed");
     }
     catch (Exception ex)
     {
         logger.Warn(ex);
         Close();
         throw new ConnectionLostException("Could not send", ex);
     }
     finally
     {
         semaphore.Release();
     }
 }