コード例 #1
0
ファイル: TcpServer.cs プロジェクト: xingx001/SuperNAT
 public TcpServer(ServerOption serverOption) : base(null)//不需要过滤器,原样转发
 {
     InitOption(serverOption);
     OnConnected += Connected;
     OnReceived  += Received;
     OnClosed    += Closed;
 }
コード例 #2
0
        private static void ServerHostInit(ServerOption option)
        {
            if (option.AppSettings != null)
            {
                List <NameValue> list = new List <NameValue>();

                foreach (AppSetting setting in option.AppSettings)
                {
                    if (setting.Key.StartsWithIgnoreCase("proxy-rule"))
                    {
                        string value = setting.Value;
                        if (string.IsNullOrEmpty(value) == false)
                        {
                            // value format: /v20/api/xxx-service/ = http://www.abc.com/
                            string[] items = value.SplitTrim('=');
                            if (items.Length == 2)
                            {
                                list.Add(new NameValue(items[0], items[1]));
                            }
                        }
                    }
                }

                if (list.Count > 0)
                {
                    s_rules = list.ToArray();
                }
            }
        }
コード例 #3
0
ファイル: Webman.cs プロジェクト: StarmanX32/StarmanLib
        public void OnlineServers(ServerOption option)
        {
            if (option == ServerOption.BlockConnection)
            {
                WebRequest  cidpsid = WebRequest.Create("http://" + ip + "/browser.ps3$block_servers");
                WebResponse rsp     = cidpsid.GetResponse();

                using (Stream dataStream = rsp.GetResponseStream())
                {
                    StreamReader rd = new StreamReader(dataStream);
                    rd.ReadToEnd();
                }
            }
            else if (option == ServerOption.RestoreConnection)
            {
                WebRequest  cidpsid = WebRequest.Create("http://" + ip + "/browser.ps3$restore_servers");
                WebResponse rsp     = cidpsid.GetResponse();

                using (Stream dataStream = rsp.GetResponseStream())
                {
                    StreamReader rd = new StreamReader(dataStream);
                    rd.ReadToEnd();
                }
            }
        }
コード例 #4
0
        private void WriteInfo(ServerOption option, string name)
        {
            AddInfoText($"You have successfully connected to {name}'s server");
            switch (option)
            {
            case ServerOption.freeplay:
                AddInfoText("The server's gamemode is set to free play, you will play against " +
                            "\nyour opponent for infinite number of games");
                break;

            case ServerOption.twoP:
                AddInfoText("The server's gamemode is set to Two player tournament, you will play\n" +
                            " 5 games against your opponent and the player with most wins will win!");
                break;

            case ServerOption.fourP:
                AddInfoText("The server's gamemode is set to Four player tournament, you will play\n" +
                            " 3 games against your first opponent and then if you win you will play at the finals!");
                break;

            case ServerOption.eightP:
                AddInfoText("The server's gamemode is set Eight player tournament, you will play\n" +
                            " 3 games against your first opponent and then if you win you will play at the semi-finals \n" +
                            "and then if you win you will play at the finals!");
                break;
            }
            AddInfoText("The right racket is your racket, the left racket is your enemy's racket");
            AddInfoText("Press escape to exit and press f11 to exit fullscreen");
            string playerOrPlayers = option == ServerOption.freeplay || option == ServerOption.twoP ? "player" : "players";

            AddInfoText($"\nWaiting for other {playerOrPlayers} to join...");
        }
コード例 #5
0
 public HttpServer(ServerOption serverOption) : base(new HttpReceiveFilter())
 {
     InitOption(serverOption);
     OnConnected += Connected;
     OnReceived  += Received;
     OnClosed    += Closed;
     WriteRequest();
 }
コード例 #6
0
 public async Task SaveOutputServerDetailsAsync(ServerOption serverOption)
 {
     if (_userPreference == null)
     {
         return;
     }
     _userPreference.OutputServer = serverOption;
     await WritereferenceToFileAsync();
 }
コード例 #7
0
 private void DeleteServerOption(Option option, ServerOption serverOption)
 {
     if (NetCache.Get().ClientOptionExists(serverOption))
     {
         object prevVal = this.GetServerOption(option, serverOption);
         NetCache.Get().DeleteClientOption(serverOption);
         this.RemoveListeners(option, prevVal);
     }
 }
コード例 #8
0
        public Tuple <string, bool, ServerOption> ReciveServerFirstAnswer()
        {
            byte[] buffer = new byte[12];
            this.stream.Read(buffer, 0, 12);
            string       name         = Utilities.ByteArrayToString(buffer.Take(10).Where(b => b != 0).ToArray());
            bool         isAccepted   = buffer[10] != 0;
            ServerOption serverOption = (ServerOption)Convert.ToInt32(buffer[11]);

            return(new Tuple <string, bool, ServerOption>(name, isAccepted, serverOption));
        }
コード例 #9
0
 public static void ServerHostInit(ServerOption option)
 {
     if (option.Website?.StaticFiles?.Length > 0)
     {
         foreach (var x in option.Website.StaticFiles)
         {
             s_mineTable[x.Ext] = x;
         }
     }
 }
コード例 #10
0
    private void GetServerOptionFlagInfo(ServerOptionFlag flag, out ServerOption container, out ulong flagBit, out ulong existenceBit)
    {
        int num   = (int)(ServerOptionFlag.HAS_SEEN_TOURNAMENT * flag);
        int index = Mathf.FloorToInt(num * 0.015625f);
        int num3  = num % 0x40;
        int num4  = 1 + num3;

        container    = s_serverFlagContainers[index];
        flagBit      = ((ulong)1L) << num3;
        existenceBit = ((ulong)1L) << num4;
    }
コード例 #11
0
        /// <summary>
        /// 根据指定的参数对象启动监听服务
        /// </summary>
        /// <param name="option"></param>
        public void Run(ServerOption option)
        {
            if (option == null)
            {
                throw new ArgumentNullException(nameof(option));
            }

            // 先将参数克隆一份,避免调用代码后期修改参数对象
            ServerOption option2 = option.CloneObject();

            InternalInit(option2);
        }
コード例 #12
0
    private void BuildServerOptionMap(Map <string, Option> options)
    {
        this.m_serverOptionMap = new Map <Option, ServerOption>();
        IEnumerator enumerator = Enum.GetValues(typeof(ServerOption)).GetEnumerator();

        try
        {
            while (enumerator.MoveNext())
            {
                ServerOption current = (ServerOption)((int)enumerator.Current);
                switch (current)
                {
                case ServerOption.INVALID:
                case ServerOption.LIMIT:
                {
                    continue;
                }
                }
                string key = current.ToString();
                if (!key.StartsWith("FLAGS") && !key.StartsWith("DEPRECATED"))
                {
                    Option option2;
                    if (!options.TryGetValue(key, out option2))
                    {
                        Debug.LogError(string.Format("Options.BuildServerOptionMap() - ServerOption {0} is not mirrored in the Option enum", current));
                    }
                    else
                    {
                        System.Type type;
                        if (!OptionDataTables.s_typeMap.TryGetValue(option2, out type))
                        {
                            Debug.LogError(string.Format("Options.BuildServerOptionMap() - ServerOption {0} has no type. Please add its type to the type map.", current));
                            continue;
                        }
                        if (type == typeof(bool))
                        {
                            Debug.LogError(string.Format("Options.BuildServerOptionMap() - ServerOption {0} is a bool. You should convert it to a ServerOptionFlag.", current));
                            continue;
                        }
                        this.m_serverOptionMap.Add(option2, current);
                    }
                }
            }
        }
        finally
        {
            IDisposable disposable = enumerator as IDisposable;
            if (disposable == null)
            {
            }
            disposable.Dispose();
        }
    }
コード例 #13
0
        private static void ServerHostInit(ServerOption option)
        {
            if (option.Website?.StaticFiles?.Length > 0)
            {
                option.InternalOptions.StaticFileExtNames
                    = (from x in option.Website.StaticFiles
                       select x.Ext
                       ).ToDictionary(x => x, x => 1, StringComparer.OrdinalIgnoreCase);
            }

            StaticFileHandler.ServerHostInit(option);
        }
コード例 #14
0
 public void SendServerFirstAnswer(bool isAccepted, string name, ServerOption serverOption)
 {
     byte[] nameArr = Utilities.StringToByteArray(name);
     byte[] toSend  = new byte[12];
     for (int i = 0; i < nameArr.Length; i++)
     {
         toSend[i] = nameArr[i];
     }
     toSend[10] = Convert.ToByte(isAccepted? 1 : 0);
     toSend[11] = Convert.ToByte((int)serverOption);
     this.stream.Write(toSend, 0, toSend.Length);
 }
コード例 #15
0
        private void InternalInit(ServerOption option)
        {
            if (_option != null)
            {
                throw new InvalidOperationException("不要重复调用Run方法。");
            }

            ServerOptionValidator validator = new ServerOptionValidator();

            validator.Validate(option);
            validator.SetDefaultValues(option);


            if (option.HandlerTypes != null)
            {
                // 注册HttpHandlerFactory
                foreach (Type handlerType in option.HandlerTypes)
                {
                    var factory = Activator.CreateInstance(handlerType) as IHttpHandlerFactory;
                    HttpHandlerFactory.GetInstance().RegisterFactory(factory);
                    ExecuuteServerHostInit(option, handlerType);
                }
            }

            if (option.ModuleTypes != null)
            {
                // 注册HttpModule
                foreach (Type moduleType in option.ModuleTypes)
                {
                    ExtenderManager.RegisterSubscriber(moduleType);
                    ExecuuteServerHostInit(option, moduleType);
                }
            }


            // 加载当前目录下的所有程序集
            AssemblyLoader.LoadAssemblies(AppDomain.CurrentDomain.BaseDirectory);

            // 加载所有路由规则
            RoutingManager.Instance.LoadRoutes();

            _option = option;


            // 启动后台线程响应所有请求
            _workThread = new Thread(ServerProc);
            _workThread.IsBackground = true;
            _workThread.Start();

            // 创建HttpListener实例并初始化
            this.Start();
        }
コード例 #16
0
        private static void StartByConfig(string configPath)
        {
            if (File.Exists(configPath) == false)
            {
                throw new ApplicationException("指定的配置文件不存在:" + configPath);
            }


            // 启动 HTTP Server
            ServerOption option = LoadConfig(configPath);

            StartByConfig(option);
        }
コード例 #17
0
        public void Listen(ServerOption options, Action action = null)
        {
            this.HttpListener = new HttpListener();
            this.HttpListener.Prefixes.Add($"http://{options.Host ?? "+"}:{options.Port}");
            this.HttpListener.BeginGetContext(new AsyncCallback(OnGetContext), this.HttpListener);
            this.HttpListener.Start();

            if (action == null)
            {
                return;
            }

            action();
        }
コード例 #18
0
        public override void Start(IPEndPoint ep, ServerOption option)
        {
            try
            {
                m_serverOption = option;


                if (m_blnRunning)
                {
                    return;
                }
                m_blnRunning = true;

                m_Sessions = new List <TSession>();

                m_sckServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_sckServer.Bind(ep);
                m_sckServer.Listen(10);

                m_Semaphore = new Semaphore(option.MaxConnection, option.MaxConnection);
                m_Buffer    = new byte[option.MaxConnection * option.SessionRecviceBuffer];
                m_eventPool = new Stack <SocketAsyncEventArgs>(option.MaxConnection);

                var handler = new EventHandler <SocketAsyncEventArgs>(On_Completed);

                for (int i = 0; i < option.MaxConnection; i++)
                {
                    SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                    e.SetBuffer(m_Buffer, i * option.SessionRecviceBuffer, option.SessionRecviceBuffer);
                    e.Completed += handler;
                    m_eventPool.Push(e);
                }

                for (int i = 0; i < option.AcceptObject; i++)
                {
                    SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                    e.Completed += handler;
                    StartAccept(e);
                }

                m_timerHeartbeat = new Timer(new TimerCallback(OnTimerCallback), null, option.SessionTimeOut, option.SessionTimeOut);
            }
            catch (Exception ex)
            {
                Close();

                throw ex;
            }
        }
コード例 #19
0
        private void ExecuuteServerHostInit(ServerOption option, Type type)
        {
            if (option.InternalOptions == null)
            {
                option.InternalOptions = new InternalOptions();
            }

            MethodInfo method = type.GetMethod("ServerHostInit",
                                               BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null,
                                               new Type[] { typeof(ServerOption) }, null);

            if (method != null)
            {
                method.Invoke(null, new object[] { option });
            }
        }
コード例 #20
0
        /// <summary>
        /// 根据指定的配置文件启动监听服务
        /// </summary>
        /// <param name="configPath"></param>
        public void Run(string configPath)
        {
            if (string.IsNullOrEmpty(configPath))
            {
                throw new ArgumentNullException(nameof(configPath));
            }

            if (File.Exists(configPath) == false)
            {
                throw new FileNotFoundException("没有找到配置文件:" + configPath);
            }


            ServerOption option = ClownFish.Base.Xml.XmlHelper.XmlDeserializeFromFile <ServerOption>(configPath);

            InternalInit(option);
        }
コード例 #21
0
        private static void ServerHostInit(ServerOption option)
        {
            if (option.Website?.DirectoryBrowse?.DefaultFile?.Length > 0)
            {
                string[] files = option.Website.DirectoryBrowse.DefaultFile.SplitTrim(';');

                if (files?.Length > 0 && PathHelper.GetExtension(files[0])?.Length > 1)
                {
                    option.InternalOptions.DefaultFiles = files;
                }
            }


            Stream stream = typeof(DirectoryBrowseHandlerFactory).Assembly.GetManifestResourceStream("ClownFish.HttpServer.Handlers.FileListTemplate.html");

            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
                s_template = reader.ReadToEnd();
            }
        }
コード例 #22
0
ファイル: BasePage.cs プロジェクト: ellischu/GalaxyLottoWeb
 internal static void SetSearchOrder(StuGLSearch stuGLSearch, string action, string requestId, string FileName, string LocalIP, string LocalBrowserType)
 {
     if (FileName == null)
     {
         throw new ArgumentNullException(nameof(FileName));
     }
     if (!string.IsNullOrEmpty(action) && !string.IsNullOrEmpty(requestId) && !string.IsNullOrEmpty(FileName))
     {
         string keySearchOrder = string.Format(InvariantCulture, "{0}#{1}#dtSearchOrder", LocalIP, LocalBrowserType);
         if (!ServerOption.ContainsKey(keySearchOrder))
         {
             ServerOption.Add(keySearchOrder, CreatSearchOrderDT());
         }
         using (DataTable DtSearchOrder = (DataTable)ServerOption[keySearchOrder])
         {
             if (DtSearchOrder.Rows.Count == 0 || DtSearchOrder.Rows.Count > 0 && DtSearchOrder.Rows.Find(action + requestId) == null)
             {
                 DataRow drRow = DtSearchOrder.NewRow();
                 drRow["ActionID"]       = action + requestId;
                 drRow["Action"]         = action;
                 drRow["requestId"]      = requestId;
                 drRow["urlFileName"]    = FileName;
                 drRow["strFilterRange"] = stuGLSearch.StrFilterRange;
                 drRow["sglFilterMin"]   = stuGLSearch.SglFilterMin;
                 drRow["sglFilterMax"]   = stuGLSearch.SglFilterMax;
                 ((DataTable)ServerOption[keySearchOrder]).Rows.Add(drRow);
                 //stuGLSearch.SearchOrder = false;
                 if (!dicSearchOrder.ContainsKey(action + requestId))
                 {
                     dicSearchOrder.Add(action + requestId, stuGLSearch);
                 }
                 else
                 {
                     dicSearchOrder[action + requestId] = stuGLSearch;
                 }
             }
         }
     }
 }
コード例 #23
0
 private object GetServerOption(Option option, ServerOption serverOption)
 {
     System.Type optionType = this.GetOptionType(option);
     if (optionType == typeof(int))
     {
         return(NetCache.Get().GetIntOption(serverOption));
     }
     if (optionType == typeof(long))
     {
         return(NetCache.Get().GetLongOption(serverOption));
     }
     if (optionType == typeof(float))
     {
         return(NetCache.Get().GetFloatOption(serverOption));
     }
     if (optionType == typeof(ulong))
     {
         return(NetCache.Get().GetULongOption(serverOption));
     }
     object[] messageArgs = new object[] { option, optionType };
     Error.AddDevFatal("Options.GetServerOption() - option {0} has unsupported underlying type {1}", messageArgs);
     return(null);
 }
コード例 #24
0
ファイル: HttpsServer.cs プロジェクト: vebin/SuperNAT
 public HttpsServer(ServerOption serverOption) : base(serverOption)
 {
     ReceiveFilter = new HttpReceiveFilter();
     WriteRequest();
 }
コード例 #25
0
 private bool IsConnectionSuccessfull(ServerOption serverOption) => serverOption != null && (_dbConnectionService?.IsConnectionAvailable(DbConnectionHelper.GetConnectionString(serverOption.ServerName, serverOption.Username, serverOption.Password)) ?? false);
コード例 #26
0
ファイル: NatServer.cs プロジェクト: vebin/SuperNAT
 public NatServer(ServerOption serverOption) : base(serverOption)
 {
     ReceiveFilter = new NatReceiveFilter();
 }
コード例 #27
0
 private static void StartByConfig(ServerOption option)
 {
     // 启动 HTTP Server
     HostInstance = new ServerHost();
     HostInstance.Run(option);
 }
コード例 #28
0
        public static void Start()
        {
            string defalutConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ServerOption.config");

            if (File.Exists(defalutConfigPath) == false)
            {
                throw new ApplicationException("程序启动目录下没有找到配置文件 ServerOption.config");
            }


            Init();

            string[] args = Environment.GetCommandLineArgs();

            // 没有指定启动参数,那么用默认的配置文件启动
            if (args.Length == 1)
            {
                StartByConfig(defalutConfigPath);
                return;
            }


            // 为了简单,只支持二种类型的命令行参数:
            // 1,指定一个 ServerOption.config 这样的配置文件,要求以 .config 结尾。
            // 2,指定一个目录,表示要将目录做为站点浏览,端口由程序自动选择。这种方式便于从Windows资源管理器中调用。

            string argsPath = args[1];

            if (Directory.Exists(argsPath))
            {
                // 先检查参数指定的目录下有没有ServerOption.config,如果存在就使用
                string configPath = Path.Combine(argsPath, "ServerOption.config");
                if (File.Exists(configPath))
                {
                    StartByConfig(configPath);
                    return;
                }


                // 使用当前程序目录的ServerOption.config做为基准参数
                ServerOption option = LoadConfig(defalutConfigPath);
                // 修改参数中的【站点目录】
                option.Website.LocalPath = argsPath;

                // 以参数方式启动
                StartByConfig(option);
                return;
            }


            if (File.Exists(argsPath))
            {
                if (argsPath.EndsWith(".config", StringComparison.OrdinalIgnoreCase))
                {
                    StartByConfig(argsPath);
                    return;
                }
            }

            // 参数无效
            throw new ApplicationException("无效的启动参数:" + argsPath);
        }