NetServer.cs 7.72 KB
using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;

namespace NetLib
{
    public class NetServer
    {
        WebSocketServer SererObj = null;
        Dictionary<string, WebSocketSession> DicSession = new Dictionary<string, WebSocketSession>();

        public delegate void DelSessionConnected(NetSession session);
        public event DelSessionConnected SessionConnected;

        public delegate void DelSessionClosed(NetSession session, CloseReason reason);
        public event DelSessionClosed SessionClosed;

        public delegate void DelMessageReceived(NetSession session, string value);
        public event DelMessageReceived MessageReceived;

        public delegate void DelDataReceived(NetSession session, byte[] value);
        public event DelDataReceived DataReceived;

        public delegate void DelSessionErr(NetSession session, Exception ex);
        public event DelSessionErr SessionErr;

        public bool Setup(int port, string ip = "")
        {
            bool res = false;

            if (SererObj != null)
            {
                try
                {
                    SererObj.Stop();
                }
                catch (Exception ex)
                {
                    string sErr = ex + "";
                }
                SererObj.NewSessionConnected -= WebSvr_SessionConnected;
                SererObj.SessionClosed -= WebSvr_SessionClosed;
                SererObj.NewMessageReceived -= WebSvr_MessageReceived;
                SererObj.NewDataReceived -= WebSvr_DataReceived;
                SererObj.Dispose();
            }
            SererObj = new WebSocketServer();
            if (string.IsNullOrEmpty(ip))
                res = SererObj.Setup(port);
            else
                res = SererObj.Setup(ip, port);
            if (res)
            {
                SererObj.NewSessionConnected += WebSvr_SessionConnected;
                SererObj.SessionClosed += WebSvr_SessionClosed;
                SererObj.NewMessageReceived += WebSvr_MessageReceived;
                SererObj.NewDataReceived += WebSvr_DataReceived;
            }
            return res;
        }

        private NetSession GetSession(WebSocketSession session)
        {
            NetSession res = new NetSession();
            res.ID = session.SessionID;
            res.DicPar = session.Cookies;
            if (res.DicPar == null)
                res.DicPar = new StringDictionary();
            res.LocalEndPoint = session.LocalEndPoint;
            res.RemoteEndPoint = session.RemoteEndPoint;
            return res;
        }

        private void WebSvr_SessionConnected(WebSocketSession session)
        {
            NetSession se = GetSession(session);
            SessionConnected?.Invoke(se);
            //if (session.Cookies["Pwd"] != "pwd111")
            //{
            //    session.Send("拒绝访问");
            //    session.Close();
            //}
        }

        private void WebSvr_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
        {
            NetSession se = GetSession(session);
            CloseReason value2 = (CloseReason)value;
            SessionClosed?.Invoke(se, value2);
        }

        private void WebSvr_MessageReceived(WebSocketSession session, string value)
        {
            NetSession se = GetSession(session);
            MessageReceived?.Invoke(se, value);
        }

        private void WebSvr_DataReceived(WebSocketSession session, byte[] value)
        {
            NetSession se = GetSession(session);
            DataReceived?.Invoke(se, value);
        }

        public bool IsStart
        {
            get
            {
                return ((SererObj != null) && (SererObj.State == SuperSocket.SocketBase.ServerState.Running));
            }
        }

        public bool Start()
        {
            if (SererObj == null)
                return false;
            else
                return SererObj.Start();
        }

        public void Stop()
        {
            if (SererObj != null)
                SererObj.Stop();
        }

        public void CloseSession(string ID)
        {
            if (SererObj == null)
                return;
            WebSocketSession session = SererObj.GetSessionByID(ID);
            try
            {
                session.Close();
            }
            catch (Exception ex)
            {
                string sErr = ex + "";
            }
        }

        /// <summary>
        /// 杨斌 2020-05-16
        /// </summary>
        void Send(WebSocketSession se, string msg)
        {
            try
            {
                se.Send(msg);
            }
            catch (Exception ex)
            {
                string sErr = "" + ex;
                NetSession session = GetSession(se);
                SessionErr?.Invoke(session, ex);
            }
        }
        /// <summary>
        /// 杨斌 2020-05-16
        /// </summary>
        void Send(WebSocketSession se, byte[] data)
        {
            try
            {
                se.Send(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                string sErr = "" + ex;
                NetSession session = GetSession(se);
                SessionErr?.Invoke(session, ex);
            }
        }

        public void Send(string msg)
        {
            if (SererObj == null)
                return;
            foreach (var se in SererObj.GetAllSessions())
            {
                Send(se, msg);//se.Send(msg);杨斌 2020-05-16
            }
        }

        public void Send(string msg, IEnumerable<string> IDs)
        {
            if (SererObj == null)
                return;
            foreach (var v in IDs)
            {
                WebSocketSession se = SererObj.GetSessionByID(v);
                Send(se, msg); //se.Send(msg);杨斌 2020-05-16
            }
        }

        public void Send(string msg, params string[] IDs)
        {
            if (SererObj == null)
                return;
            foreach (var v in IDs)
            {
                WebSocketSession se = SererObj.GetSessionByID(v);
                Send(se, msg);//se.Send(msg);杨斌 2020-05-16
            }
        }

        public void Send(byte[] data)
        {
            if (SererObj == null)
                return;
            foreach (var se in SererObj.GetAllSessions())
            {
                Send(se, data);// se.Send(data, 0, data.Length);杨斌 2020-05-16
            }
        }

        public void Send(byte[] data, IEnumerable<string> IDs)
        {
            if (SererObj == null)
                return;
            foreach (var v in IDs)
            {
                WebSocketSession se = SererObj.GetSessionByID(v);
                Send(se, data);//se.Send(data, 0, data.Length);杨斌 2020-05-16
            }
        }

        public void Send(byte[] data, params string[] IDs)
        {
            if (SererObj == null)
                return;
            foreach (var v in IDs)
            {
                WebSocketSession se = SererObj.GetSessionByID(v);
                Send(se, data);//se.Send(data, 0, data.Length);杨斌 2020-05-16
            }
        }
    }

    public class NetSession
    {
        public string ID = "";
        public string No = "";//杨斌 2020-05-16
        public IPEndPoint RemoteEndPoint = null;
        public IPEndPoint LocalEndPoint = null;
        public StringDictionary DicPar = null;
    }

    public enum CloseReason
    {
        Unknown = 0,
        ServerShutdown = 1,
        ClientClosing = 2,
        ServerClosing = 3,
        ApplicationError = 4,
        SocketError = 5,
        TimeOut = 6,
        ProtocolError = 7,
        InternalError = 8
    }
}