Exemple #1
0
        static void Main(string[] args)
        {
            IoAcceptor       acceptor = new LoopbackAcceptor();
            LoopbackEndPoint lep      = new LoopbackEndPoint(8080);

            // Set up server
            acceptor.Handler = new TennisPlayer();
            acceptor.Bind(lep);

            // Connect to the server.
            LoopbackConnector connector = new LoopbackConnector();

            connector.Handler = new TennisPlayer();
            IConnectFuture future = connector.Connect(lep);

            future.Await();
            IoSession session = future.Session;

            // Send the first ping message
            session.Write(new TennisBall(10));

            // Wait until the match ends.
            session.CloseFuture.Await();

            acceptor.Unbind();
        }
Exemple #2
0
        private void KeepAliveFilterForIdleStatus(IdleStatus status)
        {
            using (AsyncSocketConnector connector = new AsyncSocketConnector())
            {
                KeepAliveFilter filter = new KeepAliveFilter(new ClientFactory(), status, KeepAliveRequestTimeoutHandler.Exception, INTERVAL, TIMEOUT);
                filter.ForwardEvent = true;
                connector.FilterChain.AddLast("keep-alive", filter);

                Boolean gotException = false;
                connector.ExceptionCaught += (s, e) =>
                {
                    // A KeepAliveRequestTimeoutException will be thrown if no keep-alive response is received.
                    Console.WriteLine(e.Exception);
                    gotException = true;
                };

                IConnectFuture future  = connector.Connect(new IPEndPoint(IPAddress.Loopback, port)).Await();
                IoSession      session = future.Session;
                Assert.IsNotNull(session);

                Thread.Sleep((INTERVAL + TIMEOUT + 3) * 1000);

                Assert.IsFalse(gotException, "got an exception on the client");

                session.Close(true);
            }
        }
Exemple #3
0
        public IoSession Open(SerialPortConfig config = null)
        {
            using (var scope = ObjectHost.Host.BeginLifetimeScope())
            {
                if (!IsOpened())
                {
                    try
                    {
                        config = config ?? new SerialPortConfig();
                        endpoint = new SerialEndPoint(config.PortName, config.BaudRate);
                        var serial = new SerialConnector();
                        serial.FilterChain.AddLast("logger", new LoggingFilter());
                        serial.FilterChain.AddLast("codec", new ProtocolCodecFilter(new PacketCodecFactory()));
                        serial.FilterChain.AddLast("exceptionCounter", scope.Resolve<ExceptionCounterFilter>());
                        serial.Handler = scope.Resolve<PacketHandler>();
                        serial.SessionCreated += (sender, e) =>
                        {
                            e.Session.SetAttributeIfAbsent(KeyName.SESSION_ERROR_COUNTER, 0);
                        };
                        future = serial.Connect(endpoint);
                        future.Await();
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ErrorCode.SerialPortSessionOpenError, ex);
                        throw new SerialSessionOpenException(endpoint, ex);
                    }
                }
            }

            if (IsOpened()) return future.Session;
            else throw new SerialSessionOpenException(endpoint);
        }
Exemple #4
0
        public void TestUnbindDisconnectsClients()
        {
            Bind(true);
            IoConnector connector = NewConnector();

            IoSession[] sessions = new IoSession[5];
            for (int i = 0; i < sessions.Length; i++)
            {
                IConnectFuture future = connector.Connect(CreateEndPoint(port));
                future.Await();
                sessions[i] = future.Session;
                Assert.IsTrue(sessions[i].Connected);
                Assert.IsTrue(sessions[i].Write(IoBuffer.Allocate(1)).Await().Written);
            }

            // Wait for the server side sessions to be created.
            Thread.Sleep(500);

            ICollection <IoSession> managedSessions = acceptor.ManagedSessions.Values;

            Assert.AreEqual(5, managedSessions.Count);

            acceptor.Unbind();

            // Wait for the client side sessions to close.
            Thread.Sleep(500);

            //Assert.AreEqual(0, managedSessions.Count);
            foreach (IoSession element in managedSessions)
            {
                Assert.IsFalse(element.Connected);
            }
        }
        public void TestConnectFutureSuccessTiming()
        {
            Int32      port     = 12345;
            IoAcceptor acceptor = CreateAcceptor();

            acceptor.Bind(CreateEndPoint(port));

            StringBuilder buf = new StringBuilder();

            try
            {
                IoConnector connector = CreateConnector();
                connector.SessionCreated  += (s, e) => buf.Append("1");
                connector.SessionOpened   += (s, e) => buf.Append("2");
                connector.ExceptionCaught += (s, e) => buf.Append("X");

                IConnectFuture future = connector.Connect(CreateEndPoint(port));
                future.Await();
                buf.Append("3");
                future.Session.Close(true);
                // sessionCreated() will fire before the connect future completes
                // but sessionOpened() may not
                Assert.IsTrue(new Regex("12?32?").IsMatch(buf.ToString()));
            }
            finally
            {
                acceptor.Unbind();
                acceptor.Dispose();
            }
        }
        public virtual void TestConnectFutureFailureTiming()
        {
            Int32         port = 12345;
            StringBuilder buf  = new StringBuilder();

            IoConnector connector = CreateConnector();

            connector.SessionCreated  += (s, e) => buf.Append("X");
            connector.SessionOpened   += (s, e) => buf.Append("Y");
            connector.ExceptionCaught += (s, e) => buf.Append("Z");

            try
            {
                IConnectFuture future = connector.Connect(CreateEndPoint(port));
                future.Await();
                buf.Append("1");
                try
                {
                    future.Session.Close(true);
                    Assert.Fail();
                }
                catch
                {
                    // Signifies a successful test execution
                    Assert.IsTrue(true);
                }
                Assert.AreEqual("1", buf.ToString());
            }
            finally
            {
                connector.Dispose();
            }
        }
Exemple #7
0
        public void TestClientToServer()
        {
            IoAcceptor  acceptor  = new LoopbackAcceptor();
            IoConnector connector = new LoopbackConnector();

            StringBuilder actual = new StringBuilder();

            acceptor.MessageReceived += (s, e) => actual.Append(e.Message);
            acceptor.SessionClosed   += (s, e) => actual.Append("C");
            acceptor.SessionOpened   += (s, e) => actual.Append("A");

            acceptor.Bind(new LoopbackEndPoint(1));

            connector.SessionOpened += (s, e) => e.Session.Write("B");
            connector.MessageSent   += (s, e) => e.Session.Close(true);

            IConnectFuture future = connector.Connect(new LoopbackEndPoint(1));

            future.Await();
            future.Session.CloseFuture.Await();
            acceptor.Unbind();
            acceptor.Dispose();
            connector.Dispose();

            // sessionClosed() might not be invoked yet
            // even if the connection is closed.
            while (actual.ToString().IndexOf("C") < 0)
            {
                Thread.Yield();
            }

            Assert.AreEqual("ABC", actual.ToString());
        }
 void OnConnect(IoSession session, IConnectFuture future)
 {
     Session = session;
     GameThread.NextUpdate(x =>
     {
         OnConnectComplete();
     });
 }
Exemple #9
0
 private void OnConnect(IoSession session, IConnectFuture future)
 {
     if (future.Canceled || future.Exception != null)
     {
         SessionClosed(session);
     }
     this.Session = session;
 }
Exemple #10
0
        /// <summary>
        /// Main
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string Input;

            string Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            ScreenOutput("Program MyMinaTcpTimeClient Version " + Version, ConsoleColor.Green);
            ScreenOutput("use MyMinaTcpTimeClient 192.168.0.222 4712 for another server", ConsoleColor.White);
            ScreenOutput("default is 127.0.0.1:4711\n", ConsoleColor.White);
            ScreenOutput("press [Ctrl] C to exit\n", ConsoleColor.Green);

            IpAddress = "127.0.0.1";
            Port      = 4711;

            if (args.Length >= 1)
            {
                IpAddress = args[0];
            }
            if (args.Length >= 2)
            {
                Port = Convert.ToInt32(args[1]);
            }

            ScreenOutput(String.Format("We connect to {0}:{1}", IpAddress, Port.ToString()));

            IoConnector acceptor = new AsyncSocketConnector();

            acceptor.FilterChain.AddLast("logger", new LoggingFilter());
            acceptor.FilterChain.AddLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Encoding.UTF8)));

            // Set the handlers
            acceptor.ExceptionCaught += (s, e) => ScreenOutput(e.Exception.Message);
            acceptor.SessionIdle     += (s, e) => ScreenOutput("IDLE ");
            acceptor.SessionCreated  += (s, e) => ScreenOutput("Connected to " + e.Session.RemoteEndPoint);
            acceptor.SessionClosed   += (s, e) => ScreenOutput("Close connected to " + e.Session.RemoteEndPoint);
            acceptor.MessageReceived += (s, e) => ScreenOutput(e.Message.ToString());


            acceptor.SessionConfig.ReadBufferSize = 2048;
            acceptor.SessionConfig.SetIdleTime(IdleStatus.BothIdle, 10);

            IConnectFuture Future = acceptor.Connect(new IPEndPoint(IPAddress.Parse(IpAddress), Port));

            Future.Await();
            try
            {
                IoSession Session = Future.Session;
            }
            catch (Exception ex)
            {
                ScreenOutput(String.Format("{0}", ex.Message), ConsoleColor.Red);
            }

            Input = Console.ReadLine();
        }
Exemple #11
0
        private static readonly long CONNECT_TIMEOUT = 30 * 1000L;         // 30 seconds

        public static void Main(string[] args)
        {
            AsyncSocketConnector connector = new AsyncSocketConnector();

            // Configure the service.
            connector.ConnectTimeoutInMillis = CONNECT_TIMEOUT;

            connector.FilterChain.AddLast("codec",
                                          new ProtocolCodecFilter(new TextLineCodecFactory(System.Text.Encoding.UTF8,
                                                                                           LineDelimiter.Unix, LineDelimiter.Unix)));

            connector.FilterChain.AddLast("logger", new LoggingFilter());

            connector.SessionOpened += (s, e) =>
            {
                string message = "{\"type\":\"A\",\"name\":\"B\"}";
                e.Session.Write(message);
            };

            connector.ExceptionCaught += (s, e) =>
            {
                Console.WriteLine(e.Exception);
                e.Session.Close(true);
            };

            connector.MessageReceived += (s, e) =>
            {
                string message = (string)e.Message;

                System.Console.WriteLine(message);
            };

            IoSession session;

            while (true)
            {
                try
                {
                    IConnectFuture future = connector.Connect(new IPEndPoint(IPAddress.Loopback, PORT));
                    future.Await();
                    session = future.Session;
                    break;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Thread.Sleep(3000);
                }
            }

            // wait until the summation is done
            session.CloseFuture.Await();
            Console.WriteLine("Press any key to exit");
            Console.Read();
        }
        public void TestSessionCallbackInvocation()
        {
            Int32 callbackInvoked       = 0;
            Int32 sessionCreatedInvoked = 1;
            Int32 sessionCreatedInvokedBeforeCallback = 2;

            Boolean[]      assertions = { false, false, false };
            CountdownEvent countdown  = new CountdownEvent(2);

            IConnectFuture[] callbackFuture = new IConnectFuture[1];

            Int32 port = 12345;

            IoAcceptor  acceptor  = CreateAcceptor();
            IoConnector connector = CreateConnector();

            try
            {
                acceptor.Bind(CreateEndPoint(port));

                connector.SessionCreated += (s, e) =>
                {
                    assertions[sessionCreatedInvoked] = true;
                    assertions[sessionCreatedInvokedBeforeCallback] = !assertions[callbackInvoked];
                    countdown.Signal();
                };

                IConnectFuture future = connector.Connect(CreateEndPoint(port), (s, f) =>
                {
                    assertions[callbackInvoked] = true;
                    callbackFuture[0]           = f;
                    countdown.Signal();
                });

                Assert.IsTrue(countdown.Wait(TimeSpan.FromSeconds(5)), "Timed out waiting for callback and IoHandler.sessionCreated to be invoked");
                Assert.IsTrue(assertions[callbackInvoked], "Callback was not invoked");
                Assert.IsTrue(assertions[sessionCreatedInvoked], "IoHandler.sessionCreated was not invoked");
                Assert.IsFalse(assertions[sessionCreatedInvokedBeforeCallback], "IoHandler.sessionCreated was invoked before session callback");
                Assert.AreSame(future, callbackFuture[0], "Callback future should have been same future as returned by connect");
            }
            finally
            {
                try
                {
                    connector.Dispose();
                }
                finally
                {
                    acceptor.Dispose();
                }
            }
        }
 /// <summary>
 /// StartServer
 /// </summary>
 public void ConnectToServer()
 {
     try
     {
         IConnectFuture Future = Connector.Connect(new IPEndPoint(ServerIpAddress, Port));
         Future.Await();
         Session = Future.Session;
     }
     catch (Exception ex)
     {
         Console.WriteLine(String.Format("Exception {0}", ex.Message));
     }
 }
 public override void SessionCreated(INextFilter nextFilter, IoSession session)
 {
     try
     {
         session.Handler.SessionCreated(session);
     }
     finally
     {
         IConnectFuture future = session.RemoveAttribute(SessionCreatedFuture) as IConnectFuture;
         if (future != null)
         {
             future.SetSession(session);
         }
     }
 }
Exemple #15
0
        public void TestDatagramRecycler()
        {
            int port = 1024;
            ExpiringSessionRecycler recycler = new ExpiringSessionRecycler(1, 1);

            MockHandler acceptorHandler  = new MockHandler();
            MockHandler connectorHandler = new MockHandler();

            acceptor.Handler         = acceptorHandler;
            acceptor.SessionRecycler = recycler;
            acceptor.Bind(new IPEndPoint(IPAddress.Loopback, port));

            try
            {
                connector.Handler = connectorHandler;
                IConnectFuture future = connector.Connect(new IPEndPoint(IPAddress.Loopback, port));
                future.Await();

                // Write whatever to trigger the acceptor.
                future.Session.Write(IoBuffer.Allocate(1)).Await();

                // Close the client-side connection.
                // This doesn't mean that the acceptor-side connection is also closed.
                // The life cycle of the acceptor-side connection is managed by the recycler.
                future.Session.Close(true);
                future.Session.CloseFuture.Await();
                Assert.IsTrue(future.Session.CloseFuture.Closed);

                // Wait until the acceptor-side connection is closed.
                while (acceptorHandler.session == null)
                {
                    Thread.Yield();
                }
                acceptorHandler.session.CloseFuture.Await(3000);

                // Is it closed?
                Assert.IsTrue(acceptorHandler.session.CloseFuture.Closed);

                Thread.Sleep(1000);

                Assert.AreEqual("CROPSECL", connectorHandler.result.ToString());
                Assert.AreEqual("CROPRECL", acceptorHandler.result.ToString());
            }
            finally
            {
                acceptor.Unbind();
            }
        }
Exemple #16
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine(typeof(Program).FullName + " <hostname> <port>");
                return;
            }

            // Create TCP/IP connector.
            AsyncSocketConnector connector = new AsyncSocketConnector();

            // Set connect timeout.
            connector.ConnectTimeoutInMillis = 30 * 1000L;

            // Set reader idle time to 10 seconds.
            // sessionIdle(...) method will be invoked when no data is read
            // for 10 seconds.
            connector.SessionOpened += (s, e) => e.Session.Config.SetIdleTime(IdleStatus.ReaderIdle, 10);

            // Print out total number of bytes read from the remote peer.
            connector.SessionClosed += (s, e) => Console.WriteLine("Total " + e.Session.ReadBytes + " byte(s)");

            connector.SessionIdle += (s, e) =>
            {
                if (e.IdleStatus == IdleStatus.ReaderIdle)
                {
                    e.Session.Close(true);
                }
            };

            connector.MessageReceived += (s, e) =>
            {
                IoBuffer buf = (IoBuffer)e.Message;
                while (buf.HasRemaining)
                {
                    Console.Write((Char)buf.Get());
                }
            };

            // Start communication.
            IConnectFuture cf = connector.Connect(new IPEndPoint(Dns.GetHostEntry(args[0]).AddressList[3], Int32.Parse(args[1])));

            // Wait for the connection attempt to be finished.
            cf.Await();
            cf.Session.CloseFuture.Await();

            connector.Dispose();
        }
Exemple #17
0
        public void TestUnbindResume()
        {
            Bind(true);
            IoConnector connector = NewConnector();
            IoSession   session   = null;

            IConnectFuture future = connector.Connect(CreateEndPoint(port));

            future.Await();
            session = future.Session;
            Assert.IsTrue(session.Connected);
            Assert.IsTrue(session.Write(IoBuffer.Allocate(1)).Await().Written);

            // Wait for the server side session to be created.
            Thread.Sleep(500);

            ICollection <IoSession> managedSession = acceptor.ManagedSessions.Values;

            Assert.AreEqual(1, managedSession.Count);

            acceptor.Unbind();

            // Wait for the client side sessions to close.
            Thread.Sleep(500);

            //Assert.AreEqual(0, managedSession.Count);
            foreach (IoSession element in managedSession)
            {
                Assert.IsFalse(element.Connected);
            }

            // Rebind
            Bind(true);

            // Check again the connection
            future = connector.Connect(CreateEndPoint(port));
            future.Await();
            session = future.Session;
            Assert.IsTrue(session.Connected);
            Assert.IsTrue(session.Write(IoBuffer.Allocate(1)).Await().Written);

            // Wait for the server side session to be created.
            Thread.Sleep(500);

            managedSession = acceptor.ManagedSessions.Values;
            Assert.AreEqual(1, managedSession.Count);
        }
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            String server = textBoxServer.Text;

            if (String.IsNullOrEmpty(server))
            {
                return;
            }

            if (checkBoxSSL.Checked)
            {
                if (!connector.FilterChain.Contains("ssl"))
                {
                    connector.FilterChain.AddFirst("ssl", new SslFilter("TempCert", null));
                }
            }
            else if (connector.FilterChain.Contains("ssl"))
            {
                connector.FilterChain.Remove("ssl");
            }

            IPEndPoint ep;

            String[] parts = server.Trim().Split(':');
            if (parts.Length > 0)
            {
                ep = new IPEndPoint(IPAddress.Parse(parts[0]), Int32.Parse(parts[1]));
            }
            else
            {
                ep = new IPEndPoint(IPAddress.Loopback, Int32.Parse(parts[0]));
            }

            IConnectFuture future = connector.Connect(ep).Await();

            if (future.Connected)
            {
                session = future.Session;
                session.Write("LOGIN " + textBoxUser.Text);
            }
            else
            {
                MessageBox.Show("Could not connect to " + server);
            }
        }
Exemple #19
0
        private void CallNextExceptionCaught(IEntry <IoFilter, INextFilter> entry, IoSession session, Exception cause)
        {
            // Notify the related future.
            IConnectFuture future = session.RemoveAttribute(SessionCreatedFuture) as IConnectFuture;

            if (future == null)
            {
                CallNext(entry, (filter, next) => filter.ExceptionCaught(next, session, cause),
                         e => log.Warn("Unexpected exception from exceptionCaught handler.", e));
            }
            else
            {
                // Please note that this place is not the only place that
                // calls ConnectFuture.setException().
                session.Close(true);
                future.Exception = cause;
            }
        }
Exemple #20
0
        static void Main(string[] args)
        {
            IoConnector serial = new SerialConnector();

            // Add two filters : a logger and a codec
            serial.FilterChain.AddLast("logger", new LoggingFilter());
            serial.FilterChain.AddLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Encoding.UTF8)));

            serial.ExceptionCaught += (s, e) => e.Session.Close(true);
            serial.MessageReceived += (s, e) =>
            {
                Console.WriteLine(e.Message);
            };

            SerialEndPoint serialEP = new SerialEndPoint("COM3", 38400);
            IConnectFuture future   = serial.Connect(serialEP);

            future.Await();

            if (future.Connected)
            {
                while (true)
                {
                    String line = Console.ReadLine();
                    if (line.Trim().Equals("quit", StringComparison.OrdinalIgnoreCase))
                    {
                        future.Session.Close(true);
                        break;
                    }
                    future.Session.Write(line);
                }
            }
            else if (future.Exception != null)
            {
                Console.WriteLine(future.Exception);
            }

            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();
        }
Exemple #21
0
        public void TestSessionCreated()
        {
            Semaphore        semaphore = new Semaphore(0, 10);
            StringBuilder    sb        = new StringBuilder();
            LoopbackAcceptor acceptor  = new LoopbackAcceptor();
            LoopbackEndPoint lep       = new LoopbackEndPoint(12345);

            acceptor.SessionCreated += (s, e) =>
            {
                // pretend we are doing some time-consuming work. For
                // performance reasons, you would never want to do time
                // consuming work in sessionCreated.
                // However, this increases the likelihood of the timing bug.
                Thread.Sleep(1000);
                sb.Append("A");
            };
            acceptor.SessionOpened   += (s, e) => sb.Append("B");
            acceptor.MessageReceived += (s, e) => sb.Append("C");
            acceptor.SessionClosed   += (s, e) =>
            {
                sb.Append("D");
                semaphore.Release();
            };

            acceptor.Bind(lep);

            LoopbackConnector connector = new LoopbackConnector();

            connector.FilterChain.AddLast("executor", new ExecutorFilter());
            IConnectFuture future = connector.Connect(lep);

            future.Await();
            future.Session.Write(IoBuffer.Wrap(new byte[1])).Await();
            future.Session.Close(false).Await();

            semaphore.WaitOne(TimeSpan.FromSeconds(1));
            acceptor.Unbind(lep);
            Assert.AreEqual(1, future.Session.WrittenBytes);
            Assert.AreEqual("ABCD", sb.ToString());
        }
Exemple #22
0
        public IoSession Open(SerialPortConfig config = null)
        {
            using (var scope = ObjectHost.Host.BeginLifetimeScope())
            {
                if (!IsOpened())
                {
                    try
                    {
                        config   = config ?? new SerialPortConfig();
                        endpoint = new SerialEndPoint(config.PortName, config.BaudRate);
                        var serial = new SerialConnector();
                        serial.FilterChain.AddLast("logger", new LoggingFilter());
                        serial.FilterChain.AddLast("codec", new ProtocolCodecFilter(new PacketCodecFactory()));
                        serial.FilterChain.AddLast("exceptionCounter", scope.Resolve <ExceptionCounterFilter>());
                        serial.Handler         = scope.Resolve <PacketHandler>();
                        serial.SessionCreated += (sender, e) =>
                        {
                            e.Session.SetAttributeIfAbsent(KeyName.SESSION_ERROR_COUNTER, 0);
                        };
                        future = serial.Connect(endpoint);
                        future.Await();
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ErrorCode.SerialPortSessionOpenError, ex);
                        throw new SerialSessionOpenException(endpoint, ex);
                    }
                }
            }

            if (IsOpened())
            {
                return(future.Session);
            }
            else
            {
                throw new SerialSessionOpenException(endpoint);
            }
        }
        void Run()
        {
            connector = new AsyncSocketConnector();

            // Configure the service.
            connector.ConnectTimeoutInMillis = CONNECT_TIMEOUT;

            connector.FilterChain.AddLast("logger", new LoggingFilter());
            //connector.FilterChain.AddLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Encoding.UTF8)));
            connector.FilterChain.AddLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
            connector.MessageReceived += MessageReceived;
            connector.MessageSent     += MessageSent;
            connector.SessionIdle     += SessionIdle;
            connector.SessionOpened   += SessionOpened;
            connector.SessionClosed   += SessionClosed;
            connector.ExceptionCaught += ExceptionCaught;

            while (true)
            {
                try
                {
                    IConnectFuture future = connector.Connect(endPoint);
                    future.Await();
                    session      = future.Session;
                    isConnected  = true;
                    isConnecting = false;
                    break;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Thread.Sleep(3000);
                }
            }

            // wait until the summation is done
            session.CloseFuture.Await();
        }
Exemple #24
0
        public void TestAcceptorFilterChain()
        {
            Int32     port        = 1024;
            IoFilter  mockFilter  = new MockFilter();
            IoHandler mockHandler = new MockHandler();

            acceptor.FilterChain.AddLast("mock", mockFilter);
            acceptor.Handler = mockHandler;
            acceptor.Bind(new IPEndPoint(IPAddress.Loopback, port));

            try
            {
                IConnectFuture future = connector.Connect(new IPEndPoint(IPAddress.Loopback, port));
                future.Await();

                IWriteFuture writeFuture = future.Session.Write(IoBuffer.Allocate(16).PutInt32(0).Flip());
                writeFuture.Await();
                Assert.IsTrue(writeFuture.Written);

                future.Session.Close(true);

                for (int i = 0; i < 30; i++)
                {
                    if (result.Length == 2)
                    {
                        break;
                    }
                    Thread.Sleep(100);
                }

                Assert.AreEqual("FH", result);
            }
            finally
            {
                acceptor.Unbind();
            }
        }
Exemple #25
0
        public void TestCloseRequest()
        {
            int port = 1024;
            ExpiringSessionRecycler recycler = new ExpiringSessionRecycler(10, 1);

            MockHandler acceptorHandler  = new MockHandler();
            MockHandler connectorHandler = new MockHandler();

            acceptor.SessionConfig.SetIdleTime(IdleStatus.ReaderIdle, 1);
            acceptor.Handler         = acceptorHandler;
            acceptor.SessionRecycler = recycler;
            acceptor.Bind(new IPEndPoint(IPAddress.Loopback, port));

            try
            {
                connector.Handler = connectorHandler;
                IConnectFuture future = connector.Connect(new IPEndPoint(IPAddress.Loopback, port));
                future.Await();

                // Write whatever to trigger the acceptor.
                future.Session.Write(IoBuffer.Allocate(1)).Await();

                // Make sure the connection is closed before recycler closes it.
                while (acceptorHandler.session == null)
                {
                    Thread.Yield();
                }
                acceptorHandler.session.Close(true);
                Assert.IsTrue(acceptorHandler.session.CloseFuture.Await(3000));

                IoSession oldSession = acceptorHandler.session;

                // Wait until all events are processed and clear the state.
                DateTime startTime = DateTime.Now;
                while (acceptorHandler.result.ToString().Length < 8)
                {
                    Thread.Yield();
                    if ((DateTime.Now - startTime).TotalMilliseconds > 5000)
                    {
                        throw new Exception();
                    }
                }
                acceptorHandler.result.Clear();
                acceptorHandler.session = null;

                // Write whatever to trigger the acceptor again.
                IWriteFuture wf = future.Session.Write(IoBuffer.Allocate(1)).Await();
                Assert.IsTrue(wf.Written);

                // Make sure the connection is closed before recycler closes it.
                while (acceptorHandler.session == null)
                {
                    Thread.Yield();
                }
                acceptorHandler.session.Close(true);
                Assert.IsTrue(acceptorHandler.session.CloseFuture.Await(3000));

                future.Session.Close(true).Await();

                Assert.AreNotSame(oldSession, acceptorHandler.session);
            }
            finally
            {
                acceptor.Unbind();
            }
        }
        public void TestSessionCallbackInvocation()
        {
            Int32 callbackInvoked = 0;
            Int32 sessionCreatedInvoked = 1;
            Int32 sessionCreatedInvokedBeforeCallback = 2;
            Boolean[] assertions = { false, false, false };
            CountdownEvent countdown = new CountdownEvent(2);
            IConnectFuture[] callbackFuture = new IConnectFuture[1];

            Int32 port = 12345;

            IoAcceptor acceptor = CreateAcceptor();
            IoConnector connector = CreateConnector();

            try
            {
                acceptor.Bind(CreateEndPoint(port));

                connector.SessionCreated += (s, e) =>
                {
                    assertions[sessionCreatedInvoked] = true;
                    assertions[sessionCreatedInvokedBeforeCallback] = !assertions[callbackInvoked];
                    countdown.Signal();
                };

                IConnectFuture future = connector.Connect(CreateEndPoint(port), (s, f) =>
                {
                    assertions[callbackInvoked] = true;
                    callbackFuture[0] = f;
                    countdown.Signal();
                });

                Assert.IsTrue(countdown.Wait(TimeSpan.FromSeconds(5)), "Timed out waiting for callback and IoHandler.sessionCreated to be invoked");
                Assert.IsTrue(assertions[callbackInvoked], "Callback was not invoked");
                Assert.IsTrue(assertions[sessionCreatedInvoked], "IoHandler.sessionCreated was not invoked");
                Assert.IsFalse(assertions[sessionCreatedInvokedBeforeCallback], "IoHandler.sessionCreated was invoked before session callback");
                Assert.AreSame(future, callbackFuture[0], "Callback future should have been same future as returned by connect");
            }
            finally
            {
                try
                {
                    connector.Dispose();
                }
                finally
                {
                    acceptor.Dispose();
                }
            }
        }
Exemple #27
0
 private void OnConnect(IoSession session, IConnectFuture future)
 {
     this.Session = session;
 }
Exemple #28
0
        static void Main(string[] args)
        {
            IoConnector connector = new AsyncDatagramConnector();

            connector.ExceptionCaught += (s, e) =>
            {
                Console.WriteLine(e.Exception);
            };
            connector.MessageReceived += (s, e) =>
            {
                Console.WriteLine("Session recv...");
            };
            connector.MessageSent += (s, e) =>
            {
                Console.WriteLine("Session sent...");
            };
            connector.SessionCreated += (s, e) =>
            {
                Console.WriteLine("Session created...");
            };
            connector.SessionOpened += (s, e) =>
            {
                Console.WriteLine("Session opened...");
            };
            connector.SessionClosed += (s, e) =>
            {
                Console.WriteLine("Session closed...");
            };
            connector.SessionIdle += (s, e) =>
            {
                Console.WriteLine("Session idle...");
            };

            IConnectFuture connFuture = connector.Connect(new IPEndPoint(IPAddress.Loopback, MemoryMonitor.port));

            connFuture.Await();

            connFuture.Complete += (s, e) =>
            {
                IConnectFuture f = (IConnectFuture)e.Future;
                if (f.Connected)
                {
                    Console.WriteLine("...connected");
                    IoSession session = f.Session;

                    for (int i = 0; i < 30; i++)
                    {
                        Int64    memory = GC.GetTotalMemory(false);
                        IoBuffer buffer = IoBuffer.Allocate(8);
                        buffer.PutInt64(memory);
                        buffer.Flip();
                        session.Write(buffer);

                        try
                        {
                            Thread.Sleep(1000);
                        }
                        catch (ThreadInterruptedException)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Not connected...exiting");
                }
            };

            Console.ReadLine();
        }
Exemple #29
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Please specify the list of any integers");
                return;
            }

            // prepare values to sum up
            int[] values = new int[args.Length];
            for (int i = 0; i < args.Length; i++)
            {
                values[i] = Int32.Parse(args[i]);
            }

            AsyncSocketConnector connector = new AsyncSocketConnector();

            // Configure the service.
            connector.ConnectTimeoutInMillis = CONNECT_TIMEOUT;

            if (USE_CUSTOM_CODEC)
            {
                connector.FilterChain.AddLast("codec",
                                              new ProtocolCodecFilter(new SumUpProtocolCodecFactory(false)));
            }
            else
            {
                connector.FilterChain.AddLast("codec",
                                              new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
            }

            connector.FilterChain.AddLast("logger", new LoggingFilter());

            connector.SessionOpened += (s, e) =>
            {
                // send summation requests
                for (int i = 0; i < values.Length; i++)
                {
                    AddMessage m = new AddMessage();
                    m.Sequence = i;
                    m.Value    = values[i];
                    e.Session.Write(m);
                }
            };

            connector.ExceptionCaught += (s, e) =>
            {
                Console.WriteLine(e.Exception);
                e.Session.Close(true);
            };

            connector.MessageReceived += (s, e) =>
            {
                // server only sends ResultMessage. otherwise, we will have to identify
                // its type using instanceof operator.
                ResultMessage rm = (ResultMessage)e.Message;
                if (rm.OK)
                {
                    // server returned OK code.
                    // if received the result message which has the last sequence
                    // number,
                    // it is time to disconnect.
                    if (rm.Sequence == values.Length - 1)
                    {
                        // print the sum and disconnect.
                        Console.WriteLine("The sum: " + rm.Value);
                        e.Session.Close(true);
                    }
                }
                else
                {
                    // seever returned error code because of overflow, etc.
                    Console.WriteLine("Server error, disconnecting...");
                    e.Session.Close(true);
                }
            };

            IoSession session;

            while (true)
            {
                try
                {
                    IConnectFuture future = connector.Connect(new IPEndPoint(IPAddress.Loopback, PORT));
                    future.Await();
                    session = future.Session;
                    break;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Thread.Sleep(3000);
                }
            }

            // wait until the summation is done
            session.CloseFuture.Await();
            Console.WriteLine("Press any key to exit");
            Console.Read();
        }
Exemple #30
0
        public void TestSuspendResumeReadWrite()
        {
            IConnectFuture future = Connect(port, new ClientIoHandler());

            future.Await();
            IoSession session = future.Session;

            // We wait for the SessionCreated() event is fired because we
            // cannot guarantee that it is invoked already.
            while (session.GetAttribute("lock") == null)
            {
                Thread.Yield();
            }

            Object sync = session.GetAttribute("lock");

            lock (sync)
            {
                Write(session, "1");
                Assert.AreEqual('1', Read(session));
                Assert.AreEqual("1", GetReceived(session));
                Assert.AreEqual("1", GetSent(session));

                session.SuspendRead();

                Thread.Sleep(100);

                Write(session, "2");
                Assert.IsFalse(CanRead(session));
                Assert.AreEqual("1", GetReceived(session));
                Assert.AreEqual("12", GetSent(session));

                session.SuspendWrite();

                Thread.Sleep(100);

                Write(session, "3");
                Assert.IsFalse(CanRead(session));
                Assert.AreEqual("1", GetReceived(session));
                Assert.AreEqual("12", GetSent(session));

                session.ResumeRead();

                Thread.Sleep(100);

                Write(session, "4");
                Assert.AreEqual('2', Read(session));
                Assert.AreEqual("12", GetReceived(session));
                Assert.AreEqual("12", GetSent(session));

                session.ResumeWrite();

                Thread.Sleep(100);

                Assert.AreEqual('3', Read(session));
                Assert.AreEqual('4', Read(session));

                Write(session, "5");
                Assert.AreEqual('5', Read(session));
                Assert.AreEqual("12345", GetReceived(session));
                Assert.AreEqual("12345", GetSent(session));

                session.SuspendWrite();

                Thread.Sleep(100);

                Write(session, "6");
                Assert.IsFalse(CanRead(session));
                Assert.AreEqual("12345", GetReceived(session));
                Assert.AreEqual("12345", GetSent(session));

                session.SuspendRead();
                session.ResumeWrite();

                Thread.Sleep(100);

                Write(session, "7");
                Assert.IsFalse(CanRead(session));
                Assert.AreEqual("12345", GetReceived(session));
                Assert.AreEqual("1234567", GetSent(session));

                session.ResumeRead();

                Thread.Sleep(100);

                Assert.AreEqual('6', Read(session));
                Assert.AreEqual('7', Read(session));

                Assert.AreEqual("1234567", GetReceived(session));
                Assert.AreEqual("1234567", GetSent(session));
            }

            session.Close(true).Await();
        }
Exemple #31
0
        public void TestSendLargeFile()
        {
            Assert.AreEqual(FILE_SIZE, file.Length, "Test file not as big as specified");

            CountdownEvent countdown = new CountdownEvent(1);

            Boolean[]   success   = { false };
            Exception[] exception = { null };

            Int32       port      = 12345;
            IoAcceptor  acceptor  = CreateAcceptor();
            IoConnector connector = CreateConnector();

            try
            {
                acceptor.ExceptionCaught += (s, e) =>
                {
                    exception[0] = e.Exception;
                    e.Session.Close(true);
                };

                Int32 index = 0;
                acceptor.MessageReceived += (s, e) =>
                {
                    IoBuffer buffer = (IoBuffer)e.Message;
                    while (buffer.HasRemaining)
                    {
                        int x = buffer.GetInt32();
                        if (x != index)
                        {
                            throw new Exception(String.Format("Integer at {0} was {1} but should have been {0}", index, x));
                        }
                        index++;
                    }
                    if (index > FILE_SIZE / 4)
                    {
                        throw new Exception("Read too much data");
                    }
                    if (index == FILE_SIZE / 4)
                    {
                        success[0] = true;
                        e.Session.Close(true);
                    }
                };

                acceptor.Bind(CreateEndPoint(port));

                connector.ExceptionCaught += (s, e) =>
                {
                    exception[0] = e.Exception;
                    e.Session.Close(true);
                };
                connector.SessionClosed += (s, e) => countdown.Signal();

                IConnectFuture future = connector.Connect(CreateEndPoint(port));
                future.Await();

                IoSession session = future.Session;
                session.Write(file);

                countdown.Wait();

                if (exception[0] != null)
                {
                    throw exception[0];
                }

                Assert.IsTrue(success[0], "Did not complete file transfer successfully");
                Assert.AreEqual(1, session.WrittenMessages, "Written messages should be 1 (we wrote one file)");
                Assert.AreEqual(FILE_SIZE, session.WrittenBytes, "Written bytes should match file size");
            }
            finally
            {
                try
                {
                    connector.Dispose();
                }
                finally
                {
                    acceptor.Dispose();
                }
            }
        }
 public void SetSessionFuture(IConnectFuture future)
 {
     if (!IsClosed)
         sessionFuture.WriteFullFence(future);
 }