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

namespace BossServer
{

    class Program
    {
        static Socket SocketWatch = null;                                       // 创建一个和客户端通信的套接字 
        const int port = 6002;                                                  // 端口号（用来监听的） 

        static void Main(string[] args)
        {
            selfTest();
            IPAddress ip = IPAddress.Any;
            IPEndPoint ipe = new IPEndPoint(ip, port);                         //将IP地址和端口号绑定到网络节点point上  

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

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

            Task.Run(WatchConnecting).Wait();                                  // 开启监听线程
            SocketWatch.Close();                                               // 结束监听socket

        }

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

                Room.Instance.AddPeer(new Peer(connection));
            }
        }

    }
}
