Exemple #1
0
        public UdpSession(UdpServer Server, Socket ServerSocket, IPEndPoint RemoteEndPoint, Func <ISessionContext, IBinaryTransformer, KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer> > VirtualTransportServerFactory, Action <Action> QueueUserWorkItem)
        {
            this.Server              = Server;
            this.ServerSocket        = ServerSocket;
            this.RemoteEndPoint      = RemoteEndPoint;
            this.LastActiveTimeValue = new LockedVariable <DateTime>(DateTime.UtcNow);
            ssm = new SessionStateMachine <StreamedVirtualTransportServerHandleResult, Unit>(ex => ex is SocketException, OnCriticalError, OnShutdownRead, OnShutdownWrite, OnWrite, OnExecute, OnStartRawRead, OnExit, QueueUserWorkItem);

            Context                = Server.ServerContext.CreateSessionContext();
            Context.Quit          += ssm.NotifyExit;
            Context.Authenticated += () => Server.NotifySessionAuthenticated(this);

            var rpst = new Rc4PacketServerTransformer();
            var Pair = VirtualTransportServerFactory(Context, rpst);

            si  = Pair.Key;
            vts = Pair.Value;
            Context.SecureConnectionRequired += c =>
            {
                rpst.SetSecureContext(c);
                NextSecureContext = c;
            };
            vts.ServerEvent           += () => ssm.NotifyWrite(new Unit());
            vts.InputByteLengthReport += (CommandName, ByteLength) => Server.ServerContext.RaiseSessionLog(new SessionLogEntry {
                Token = Context.SessionTokenString, RemoteEndPoint = RemoteEndPoint, Time = DateTime.UtcNow, Type = "InBytes", Name = CommandName, Message = ByteLength.ToInvariantString()
            });
            vts.OutputByteLengthReport += (CommandName, ByteLength) => Server.ServerContext.RaiseSessionLog(new SessionLogEntry {
                Token = Context.SessionTokenString, RemoteEndPoint = RemoteEndPoint, Time = DateTime.UtcNow, Type = "OutBytes", Name = CommandName, Message = ByteLength.ToInvariantString()
            });
        }
Exemple #2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Creating server object");
            var Server = new UdpServer();

            Console.WriteLine("Running server");
            Server.Run();
        }
Exemple #3
0
        static void Main(string[] args)
        {
            Debug.DefaultDebugger = new ServerConsoleDebugger();
            MessageProcessor.DefaultSerializer = new MsgPackBitSerializer();

            /*
             * LoginReqMsg msg = new LoginReqMsg {
             *  Account = "account",
             *  Password = "******",
             *  Extra = "去去去",
             * };
             *
             * //  var bytes = Serialize(msg);
             * var bytes = MessagePackSerializer.Serialize(msg);
             * var obj = MessagePackSerializer.Deserialize<LoginReqMsg>(bytes);
             * Console.WriteLine(MessagePackSerializer.ConvertToJson(bytes));
             */

            MessageProcessor messageProcessor = new MessageProcessor();

            messageProcessor.Run(TaskScheduler.Default);
            MessageProcessor.RegisterHandler <LoginReqMsg>((msg, fromLink) => {
                var rsp = new LoginRspMsg {
                    Player = new Model.Player {
                        Status = Model.Status.Online,
                        Name   = "二逼青年"
                    },
                    SeqNumber = msg.SeqNumber,
                };
                var bytes = MessageProcessor.PackageMessage(rsp);
                fromLink.SendToRemoteAsync(bytes.buffer, 0, bytes.len);
                //  Debug.LogFormat("{0}-{1}-{2}", msg.Account, msg.Password, msg.Extra);
            });

            var udpServer = new UdpServer(messageProcessor);

            udpServer.Start(IPAddress.Any, 8063);

            do
            {
                var input = Console.ReadLine();
            } while (true);

            /*
             * MessageProcessor.RegisterHandler<LoginReqMsg>((msg, remote) => {
             *  Debug.LogFormat("LoginReqMsg - {0}|{1}|{2}", msg.Account, msg.Password, msg.Extra);
             *  var loginReq = new LoginRspMsg {
             *      Player = new Model.Player {
             *          Name = "二逼青年",
             *          Status = Model.Status.Online,
             *          Mails = new System.Collections.Generic.Dictionary<int, Model.Mail> {
             *              {
             *                  234,
             *                  new Model.Mail {
             *                      Id = 234,
             *                      Title = "测试",
             *                      Content ="test"
             *                  }
             *              }
             *          },
             *      }
             *  };
             *  var loginReqBytes = MessageProcessor.DefaultSerializer.Serialize(
             *       MessageProcessor.PackageMessage(loginReq));
             *  udpServer.Send(loginReqBytes, remote);
             * });
             */
        }
Exemple #4
0
        private static IServer StartProtocol(Configuration c, ChatProtocolConfiguration pc, ServerContext ServerContext, TaskFactory Factory, TaskFactory PurifierFactory)
        {
            if (pc.OnTcp)
            {
                var s = pc.Tcp;

                if (!(s.SerializationProtocolType == SerializationProtocolType.Binary || s.SerializationProtocolType == SerializationProtocolType.Json))
                {
                    throw new InvalidOperationException("未知协议类型: " + s.SerializationProtocolType.ToString());
                }

                Func <ISessionContext, IBinaryTransformer, KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer> > VirtualTransportServerFactory;
                if (s.SerializationProtocolType == SerializationProtocolType.Binary)
                {
                    VirtualTransportServerFactory = (Context, t) =>
                    {
                        var p    = ServerContext.CreateServerImplementationWithBinaryAdapter(Factory, Context);
                        var si   = p.Key;
                        var a    = p.Value;
                        var bcps = new BinaryCountPacketServer(a, CommandName => true, t);
                        return(new KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer>(si, bcps));
                    };
                }
                else if (s.SerializationProtocolType == SerializationProtocolType.Json)
                {
                    VirtualTransportServerFactory = (Context, t) =>
                    {
                        var p    = ServerContext.CreateServerImplementationWithJsonAdapter(Factory, Context);
                        var si   = p.Key;
                        var a    = p.Value;
                        var bcps = new JsonLinePacketServer(a, CommandName => true, t);
                        return(new KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer>(si, bcps));
                    };
                }
                else
                {
                    throw new InvalidOperationException();
                }

                var Server  = new TcpServer(ServerContext, VirtualTransportServerFactory, a => Factory.StartNew(a), a => PurifierFactory.StartNew(a));
                var Success = false;

                try
                {
                    Server.Bindings           = s.Bindings.Select(b => new IPEndPoint(IPAddress.Parse(b.IpAddress), b.Port)).ToArray();
                    Server.SessionIdleTimeout = s.SessionIdleTimeout;
                    Server.UnauthenticatedSessionIdleTimeout = s.UnauthenticatedSessionIdleTimeout;
                    Server.MaxConnections          = s.MaxConnections;
                    Server.MaxConnectionsPerIP     = s.MaxConnectionsPerIP;
                    Server.MaxUnauthenticatedPerIP = s.MaxUnauthenticatedPerIP;
                    Server.MaxBadCommands          = s.MaxBadCommands;

                    Server.Start();

                    Console.WriteLine(@"TCP/{0}服务器已启动。结点: {1}".Formats(s.SerializationProtocolType.ToString(), String.Join(", ", Server.Bindings.Select(b => b.ToString() + "(TCP)"))));

                    Success = true;
                }
                finally
                {
                    if (!Success)
                    {
                        Server.Dispose();
                    }
                }

                return(Server);
            }
            else if (pc.OnUdp)
            {
                var s = pc.Udp;

                if (!(s.SerializationProtocolType == SerializationProtocolType.Binary || s.SerializationProtocolType == SerializationProtocolType.Json))
                {
                    throw new InvalidOperationException("未知协议类型: " + s.SerializationProtocolType.ToString());
                }

                Func <ISessionContext, IBinaryTransformer, KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer> > VirtualTransportServerFactory;
                if (s.SerializationProtocolType == SerializationProtocolType.Binary)
                {
                    VirtualTransportServerFactory = (Context, t) =>
                    {
                        var p    = ServerContext.CreateServerImplementationWithBinaryAdapter(Factory, Context);
                        var si   = p.Key;
                        var a    = p.Value;
                        var bcps = new BinaryCountPacketServer(a, CommandName => true, t);
                        return(new KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer>(si, bcps));
                    };
                }
                else if (s.SerializationProtocolType == SerializationProtocolType.Json)
                {
                    VirtualTransportServerFactory = (Context, t) =>
                    {
                        var p    = ServerContext.CreateServerImplementationWithJsonAdapter(Factory, Context);
                        var si   = p.Key;
                        var a    = p.Value;
                        var bcps = new JsonLinePacketServer(a, CommandName => true, t);
                        return(new KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer>(si, bcps));
                    };
                }
                else
                {
                    throw new InvalidOperationException();
                }

                var Server  = new UdpServer(ServerContext, VirtualTransportServerFactory, a => Factory.StartNew(a), a => PurifierFactory.StartNew(a));
                var Success = false;

                try
                {
                    Server.Bindings           = s.Bindings.Select(b => new IPEndPoint(IPAddress.Parse(b.IpAddress), b.Port)).ToArray();
                    Server.SessionIdleTimeout = s.SessionIdleTimeout;
                    Server.UnauthenticatedSessionIdleTimeout = s.UnauthenticatedSessionIdleTimeout;
                    Server.MaxConnections          = s.MaxConnections;
                    Server.MaxConnectionsPerIP     = s.MaxConnectionsPerIP;
                    Server.MaxUnauthenticatedPerIP = s.MaxUnauthenticatedPerIP;
                    Server.MaxBadCommands          = s.MaxBadCommands;

                    Server.TimeoutCheckPeriod = s.TimeoutCheckPeriod;

                    Server.Start();

                    Console.WriteLine(@"UDP/{0}服务器已启动。结点: {1}".Formats(s.SerializationProtocolType.ToString(), String.Join(", ", Server.Bindings.Select(b => b.ToString() + "(UDP)"))));

                    Success = true;
                }
                finally
                {
                    if (!Success)
                    {
                        Server.Dispose();
                    }
                }

                return(Server);
            }
            else if (pc.OnHttp)
            {
                var s = pc.Http;

                Func <ISessionContext, KeyValuePair <IServerImplementation, IHttpVirtualTransportServer> > VirtualTransportServerFactory = Context =>
                {
                    var p    = ServerContext.CreateServerImplementationWithJsonAdapter(Factory, Context);
                    var si   = p.Key;
                    var a    = p.Value;
                    var jhps = new JsonHttpPacketServer(a, CommandName => true);
                    return(new KeyValuePair <IServerImplementation, IHttpVirtualTransportServer>(si, jhps));
                };

                var Server  = new HttpServer(ServerContext, VirtualTransportServerFactory, a => Factory.StartNew(a), a => PurifierFactory.StartNew(a));
                var Success = false;

                try
                {
                    Server.Bindings           = s.Bindings.Select(b => b.Prefix).ToArray();
                    Server.SessionIdleTimeout = s.SessionIdleTimeout;
                    Server.UnauthenticatedSessionIdleTimeout = s.UnauthenticatedSessionIdleTimeout;
                    Server.MaxConnections          = s.MaxConnections;
                    Server.MaxConnectionsPerIP     = s.MaxConnectionsPerIP;
                    Server.MaxUnauthenticatedPerIP = s.MaxUnauthenticatedPerIP;
                    Server.MaxBadCommands          = s.MaxBadCommands;

                    Server.TimeoutCheckPeriod = s.TimeoutCheckPeriod;
                    Server.ServiceVirtualPath = s.ServiceVirtualPath;

                    Server.Start();

                    Console.WriteLine(@"HTTP/{0}服务器已启动。结点: {1}".Formats("Json", String.Join(", ", Server.Bindings.Select(b => b.ToString()))));

                    Success = true;
                }
                finally
                {
                    if (!Success)
                    {
                        Server.Dispose();
                    }
                }

                return(Server);
            }
            else if (pc.OnHttpStatic)
            {
                var s = pc.HttpStatic;

                var Server  = new StaticHttpServer(ServerContext, a => Factory.StartNew(a), 8 * 1024);
                var Success = false;

                try
                {
                    Server.Bindings                = s.Bindings.Select(b => b.Prefix).ToArray();
                    Server.SessionIdleTimeout      = Math.Min(s.SessionIdleTimeout, s.UnauthenticatedSessionIdleTimeout);
                    Server.MaxConnections          = s.MaxConnections;
                    Server.MaxConnectionsPerIP     = s.MaxConnectionsPerIP;
                    Server.MaxBadCommands          = s.MaxBadCommands;
                    Server.MaxUnauthenticatedPerIP = s.MaxUnauthenticatedPerIP;

                    Server.ServiceVirtualPath = s.ServiceVirtualPath;
                    Server.PhysicalPath       = s.PhysicalPath;
                    Server.Indices            = s.Indices.Split(',').Select(Index => Index.Trim(' ')).Where(Index => Index != "").ToArray();

                    Server.Start();

                    Console.WriteLine(@"HTTP静态服务器已启动。结点: {0}".Formats(String.Join(", ", Server.Bindings.Select(b => b.ToString()))));

                    Success = true;
                }
                finally
                {
                    if (!Success)
                    {
                        Server.Dispose();
                    }
                }

                return(Server);
            }
            else
            {
                throw new InvalidOperationException("未知服务器类型: " + pc._Tag.ToString());
            }
        }