示例#1
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);
            }
        }
示例#2
0
        private void Connect()
        {
            var connector = new AsyncSocketConnector();

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

            connector.ConnectTimeoutInMillis          = 10000;
            connector.SessionConfig.KeepAlive         = true;
            connector.SessionConfig.SendBufferSize    = 1024;
            connector.SessionConfig.ReceiveBufferSize = 1024 * 3;
            connector.MessageReceived += Connector_MessageReceived;
            connector.MessageSent     += Connector_MessageSent;
            connector.SessionOpened   += Connector_SessionOpened;
            connector.SessionClosed   += Connector_SessionClosed;
            IPAddress address = IPAddress.Parse(IpAddress);

            for (var i = 0; i < 5; i++)
            {
                try
                {
                    var connectFuture = connector.Connect(new IPEndPoint(address, 6667));//.Await();
                    State = ConnectingState.Connecting;
                    Debug.LogWarning("Session: " + connectFuture.Session);
                    return;
                }catch (Exception e)
                {
                    Debug.LogWarning("Error on connect: \n" + e.StackTrace);
                }
            }
        }
示例#3
0
        public void UncaughtExceptionTest()
        {
            var are       = new AutoResetEvent(false);
            var endPoint  = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001);
            var connector = new AsyncSocketConnector();

            connector.FilterChain.AddLast("fireExceptiojn", new FireExceptionFilter(are));
            connector.FilterChain.AddLast("exceptionCounter", ObjectHost.Host.Resolve <ExceptionCounterFilter>());
            connector.FilterChain.AddLast("logger", new LoggingFilter());
            connector.SessionCreated += (s, e) =>
            {
                e.Session.SetAttributeIfAbsent(KeyName.SESSION_ERROR_COUNTER, 0);
            };

            var future = connector.Connect(endPoint);

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

            var guid             = Guid.NewGuid().ToByteArray();
            var serverIdentifier = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("ctppv5_command_server")).ToHex();
            var buffer           = ByteBufferAllocator.Instance.Allocate(48);

            buffer.AutoExpand = true;
            buffer.PutInt32(49);
            buffer.Put(1);
            buffer.PutInt16(1);
            buffer.Put(ErrorCode.NoError.ToByte());
            buffer.Put(MessageType.Command.ToByte());
            buffer.Put(Guid.NewGuid().ToByteArray());
            buffer.Put(guid);
            buffer.Put((MessageFilterType.Checksum).ToByte());
            buffer.Put(new byte[] { 0, 0 });
            buffer.Put(SerializeMode.None.ToByte());
            buffer.Position = 0;
            var header = buffer.GetArray(45);

            buffer.Put(BitConverter.GetBytes(Crc32.CalculateDigest(header, (uint)0, (uint)(header.Length))));
            buffer.Position = buffer.Position - 1; // make crc error
            buffer.Put(4);

            for (int i = 0; i < 6; i++)
            {
                buffer.Flip();
                session.Write(buffer);
                are.WaitOne();
            }

            while (true)
            {
                if (session.Connected)
                {
                    Thread.Sleep(200);
                }
                else
                {
                    break;
                }
            }
        }
示例#4
0
        public void Open(ConnectionConfig config)
        {
            using (var scope = ObjectHost.Host.BeginLifetimeScope())
            {
                try
                {
                    this.endPoint = config.EndPoint;
                    connector     = new AsyncSocketConnector();
                    connector.ConnectTimeoutInMillis = config.Timeout;
                    connector.FilterChain.AddLast("logger", new LoggingFilter());
                    connector.FilterChain.AddLast("codec",
                                                  new ProtocolCodecFilter(new MessageCodecFactory()));
                    if (config.KeepAlive)
                    {
                        var keepAliveFilter = new KeepAliveFilter(
                            new KeepAliveMessageFactory(), IdleStatus.WriterIdle, KeepAliveRequestTimeoutHandler.Exception, writerIdleTime, heartbeatTimeout);
                        connector.FilterChain.AddLast("keep-alive", keepAliveFilter);
                    }
                    connector.FilterChain.AddLast("exceptionCounter", scope.Resolve <ExceptionCounterFilter>());
                    connector.Handler         = scope.Resolve <CommandHandler>();
                    connector.SessionCreated += (sender, e) =>
                    {
                        e.Session.SetAttributeIfAbsent(KeyName.SESSION_ERROR_COUNTER, 0);
                    };

                    var future = connector.Connect(endPoint);
                    future.Await();
                    sessionImpl = future.Session;
                }
                catch (Exception ex)
                {
                    throw new SessionOpenException(endPoint, ex);
                }
            }
        }
示例#5
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();
        }
示例#6
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();
        }
示例#7
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();
        }
示例#8
0
        public void ServerStartUpTest()
        {
            var bootstrap = new ServerBootstrap(EndPointDispatcher.GetRandomPort());

            Assert.IsTrue(bootstrap.StartUp());
            var connector = new AsyncSocketConnector();
            var future    = connector.Connect(bootstrap.EndPoint);

            Assert.IsTrue(future.Await(500));
            System.Threading.Thread.Sleep(500);
            Assert.AreEqual(1, bootstrap.Server.ManagedSessions.Count);
            Assert.IsTrue(future.Connected);
            Assert.IsNotNull(future.Session);
            bootstrap.Server.Dispose();
            connector.Dispose();
        }
        public void TestWriteUsingSocketTransport()
        {
            AsyncSocketAcceptor acceptor = new AsyncSocketAcceptor();
            acceptor.ReuseAddress = true;
            IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 12345);

            AsyncSocketConnector connector = new AsyncSocketConnector();

            // Generate 4MB of random data
            Byte[] data = new Byte[4 * 1024 * 1024];
            new Random().NextBytes(data);

            Byte[] expectedMd5;
            using (MD5 md5 = MD5.Create())
            {
                expectedMd5 = md5.ComputeHash(data);
            }

            M message = CreateMessage(data);

            SenderHandler sender = new SenderHandler(message);
            ReceiverHandler receiver = new ReceiverHandler(data.Length);

            acceptor.Handler = sender;
            connector.Handler = receiver;

            acceptor.Bind(ep);
            connector.Connect(ep);
            sender.countdown.Wait();
            receiver.countdown.Wait();

            acceptor.Dispose();
            connector.Dispose();

            Assert.AreEqual(data.Length, receiver.ms.Length);
            Byte[] actualMd5;
            using (MD5 md5 = MD5.Create())
            {
                actualMd5 = md5.ComputeHash(receiver.ms.ToArray());
            }
            Assert.AreEqual(expectedMd5.Length, actualMd5.Length);
            for (Int32 i = 0; i < expectedMd5.Length; i++)
            {
                Assert.AreEqual(expectedMd5[i], actualMd5[i]);
            }
        }
        /// <summary>
        /// InitializeServer
        /// </summary>
        public void InitializeClient()
        {
            Connector = new AsyncSocketConnector();
            Connector.FilterChain.AddLast("logger", new LoggingFilter());
            Mina.Filter.Stream.StreamWriteFilter SIOFilter = new Mina.Filter.Stream.StreamWriteFilter();
            Connector.FilterChain.AddLast("codec", new ProtocolCodecFilter(new ProtocolCodecFactory()));

            Connector.SessionOpened += (s, e) =>
            {
                Session = e.Session;
            };
            Connector.SessionClosed += (s, e) =>
            {
                Session = null;
            };


            Connector.SessionConfig.ReadBufferSize = 1024;
            Connector.SessionConfig.SetIdleTime(IdleStatus.BothIdle, 10);
        }
示例#11
0
        private static void ClientConnect()
        {
            using (var client = new AsyncSocketConnector())
                using (var ready = new System.Threading.ManualResetEventSlim(false))
                {
                    client.FilterChain.AddLast("ssl", new SslFilter("TempCert", null));
                    client.FilterChain.AddLast("text", new ProtocolCodecFilter(new TextLineCodecFactory()));

                    client.MessageReceived += (s, e) =>
                    {
                        Debug.WriteLine("Client got: " + e.Message);
                        ready.Set();
                    };

                    var session = client.Connect(new IPEndPoint(IPAddress.Loopback, port)).Await().Session;

                    Debug.WriteLine("Client sending: hello");
                    session.Write("hello                      ");

                    Debug.WriteLine("Client sending: send");
                    session.Write("send");

                    ready.Wait(3000);
                    Assert.IsTrue(ready.IsSet);

                    ready.Reset();
                    Assert.IsFalse(ready.IsSet);

                    Debug.WriteLine("Client sending: hello");
                    session.Write(IoBuffer.Wrap(Encoding.UTF8.GetBytes("hello                      \n")));

                    Debug.WriteLine("Client sending: send");
                    session.Write(IoBuffer.Wrap(Encoding.UTF8.GetBytes("send\n")));

                    ready.Wait(3000);
                    Assert.IsTrue(ready.IsSet);

                    session.Close(true);
                }
        }
示例#12
0
        private void makeConnectionInCallerThread(int waitInMs)
        {
            if (ioSession != null)
            {
                if (ioSession.Connected)
                {
                    return;
                }
            }
            if (connecting == 1)
            {
                return;
            }
            int orgValue = Interlocked.CompareExchange(ref connecting, 1, 0);

            if (orgValue == 1)
            {
                return;
            }
            metaHolder.requestPool.Clear();
            HostPort serverConfig = serverList [rand.Next(serverList.Count)];

            connector = new AsyncSocketConnector();
            connector.FilterChain.AddLast("codec", new ProtocolCodecFilter(new CustomPackageFactory()));
            connector.FilterChain.AddLast("logger", new LoggingFilter());
            connector.MessageReceived += onMessageReceived;
            connector.SessionOpened   += (sender, eventArgs) => {
                this.ioSession = eventArgs.Session;
                Console.WriteLine("connected.");
            };
            Console.WriteLine("connecting...");
            var addresses = System.Net.Dns.GetHostAddresses(serverConfig.host);
            var endPoint  = new IPEndPoint(addresses [0], serverConfig.port);

            try {
                connector.Connect(endPoint).Await(waitInMs);
            } finally {
                connecting = 0;
            }
        }
示例#13
0
        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();
        }
示例#14
0
文件: Client.cs 项目: xlg210/Mina.NET
        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();
        }