高级开发

Mina.Net实现的断线重连

宋兴柱 · 4月29日 · 2016年 2246次已读
using Mina.Filter.Codec;
using Mina.Filter.Codec.TextLine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Mina.Core.Session;
using System.Threading;

namespace MinaDemo
{
    class TCPMessageDemo
    {
        static string ip = "127.0.0.1";
        static int port = 1024;
        static void Main(string[] args)
        {
            Client();
        }
        static void Server()
        {
            var acceptor = new Mina.Transport.Socket.AsyncSocketAcceptor();
            acceptor.FilterChain.AddLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Encoding.UTF8)));
            acceptor.MessageReceived += (ss, ee) =>//接收到消息后
            {
                Console.WriteLine("服务端收到" + ee.Session.RemoteEndPoint + "的消息:" + ee.Message + ",并广播:I love you all");
                acceptor.Broadcast("I love you all");
                //只有服务端接收到客户端发来消息时,才会把客户端存放到acceptor.ManagedSessions中,才能广播到。超过1分钟后,如果没有收到 Session,就会自动掉线的。
            };
            acceptor.SessionCreated += (ss, ee) => { ee.Session.Config.SetIdleTime(IdleStatus.BothIdle, 10); };

            acceptor.Bind(new IPEndPoint(IPAddress.Any, port));
            Console.WriteLine("linten in port " + port);
            Console.ReadLine();
            acceptor.Unbind();
            acceptor.Dispose();
        }
        static void Client()
        {
            var connector = new Mina.Transport.Socket.AsyncSocketConnector();
            connector.FilterChain.AddLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Encoding.UTF8)));
            connector.MessageReceived += (ss, ee) =>//接收到消息后
            {
                Console.WriteLine("客户端收到" + ee.Session.RemoteEndPoint + "的消息:" + ee.Message + "");
            };
            connector.DefaultRemoteEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            var session = connector.Connect().Await().Session;
            connector.SessionClosed += (ss, ee) => { Console.WriteLine("SessionClosed"); };
            object lastSendFaileMessage = null;//记录最近一次发送的消息,如果发送失败的情况下,下次断线重连后还可以再发。
            connector.SessionDestroyed += (ss, ee) =>
            {
                Console.WriteLine("SessionDestroyed");
                //断绝重连
                while (true)
                {
                    try
                    {
                        if (!connector.Disposed)//如果不是因为客户端执行的关闭,则进行断线重连
                        {
                            Console.WriteLine("断线得连!");
                            session = connector.Connect().Await().Session;
                            Console.WriteLine("连接成功!");
                            if (!string.IsNullOrWhiteSpace(lastSendFaileMessage + "")) { session.Write(lastSendFaileMessage); }
                        }
                        else lastSendFaileMessage = null;
                        break;
                    }
                    catch (Exception ex) { Console.WriteLine("尝试失败:" + ex.Message); Thread.Sleep(1000); }
                }
            };
            while (true)
            {
                var line = Console.ReadLine();
                if (line == "exit")
                {
                    session.Close(true);
                    connector.Dispose();
                }
                if (session.Connected)
                {
                    Console.WriteLine("Connected.");
                    if (session.Write(line).Exception != null)
                    {
                        lastSendFaileMessage = line;
                    }
                }
                else
                {
                    Console.WriteLine("DisConnected.");
                }
            }
        }

    }
}

 

0 条回应