using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Diagnostics;


namespace MultiDup
{
    internal class Program
    {
        const int serverport = 6005;                                            // 用于监听服务端连接的端口号

        public static ServerPeer serverPeer = null;                             // 战斗server的连接

        const int port = 6004;                                                  // 端口号（用来监听的） 
        static void Main(string[] args)
        {
            selfTest();

            Console.WriteLine("开启监听......");
            Console.WriteLine("ctrl + c 退出程序......");

            Task[] tasks = new Task[2];
            tasks[0] = Task.Run(WatchConnecting);
            tasks[1] = Task.Run(WatchServerPeerConnecting);
            Task.WaitAll(tasks);                                                // 开启监听线程 

        }


        static void selfTest()
        {
            var rdb = Redis.Ins.GetDatabase(0);
            Debug.Assert(rdb.StringSet("test", "wanggang" + DateTime.Now.ToString("yyyyMMddHHmmss")), "Redis读写失败!");
        }

        /// <summary>
        /// 监听客户端发来的请求  
        /// </summary>
        async static Task WatchConnecting()
        {
            IPAddress ip = IPAddress.Any;
            IPEndPoint ipe = new IPEndPoint(ip, port);                         //将IP地址和端口号绑定到网络节点point上  

            //定义一个套接字用于监听客户端发来的消息，包含三个参数（IP4寻址协议，流式连接，Tcp协议）  
            Socket SocketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SocketWatch.Bind(ipe);                                             // 监听绑定的网络节点           
            SocketWatch.Listen(20);                                            // 将套接字的监听队列长度限制为20    

            while (true)                                                       // 持续不断监听客户端发来的请求     
            {
                Socket connection;
                try
                {
                    connection = await SocketWatch.AcceptAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);                             // 提示套接字监听异常     
                    break;
                }

                Lobby.Instance.OnNewPeerConnected(new Peer(connection));       // 有新客户端连入
            }
            SocketWatch.Close();                                               // 结束监听socket
        }

        /// <summary>
        /// 监听服务端发来的请求  
        /// </summary>
        async static Task WatchServerPeerConnecting()
        {
            IPAddress ip = IPAddress.Any;
            IPEndPoint ipe = new IPEndPoint(ip, serverport);                             //将IP地址和端口号绑定到网络节点point上  

            //定义一个套接字用于监听客户端发来的消息，包含三个参数（IP4寻址协议，流式连接，Tcp协议）  
            Socket SocketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SocketWatch.Bind(ipe);                                                       // 监听绑定的网络节点           
            SocketWatch.Listen(20);                                                      // 将套接字的监听队列长度限制为20    

            while (true)                                                                 // 持续不断监听客户端发来的请求     
            {
                Socket connection;
                try
                {
                    connection = await SocketWatch.AcceptAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);                                       // 提示套接字监听异常     
                    break;
                }
                Console.WriteLine("server peer 连接上来了.");
                if (null != serverPeer) { 
                    serverPeer.Close();
                }
                serverPeer = new ServerPeer(connection);                                 // 建立与服务端的连接
            }
            SocketWatch.Close();                                                         // 结束监听socket
        }
    }
}
