• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Network.NetServer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Lidgren.Network.NetServer的典型用法代码示例。如果您正苦于以下问题:C# NetServer类的具体用法?C# NetServer怎么用?C# NetServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



NetServer类属于Lidgren.Network命名空间,在下文中一共展示了NetServer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: HandleMessage

        private static void HandleMessage(NetIncomingMessage inc, NetServer server)
        {
            switch (inc.MessageType)
            {
                case NetIncomingMessageType.ConnectionApproval: //If ConnectionApproval request
                    if (inc.ReadByte() == (byte) PacketTypes.Headers.Login)
                    {
                        string username = inc.ReadString();
                        Console.WriteLine("New Login Request from: {0}", username);
                        if (username.Length > 1 & Players.Values.All(c => c.Name != username) &
                            !_badwordList.Contains(username, StringComparer.OrdinalIgnoreCase))
                        {
                            inc.SenderConnection.Approve();
                            NetOutgoingMessage connectedMessage = server.CreateMessage();
                            Thread.Sleep(500);
                            Console.WriteLine("Sending a ack to {0}", username);
                            connectedMessage.Write((byte) PacketTypes.Headers.LoggedIn);
                            connectedMessage.Write(true);
                            server.SendMessage(connectedMessage, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered);
                        }
                        else
                        {
                            inc.SenderConnection.Deny("Bad Username");
                        }
                    }

                    break;

                case NetIncomingMessageType.Data:
                    byte packetheader = inc.ReadByte();
                    HandleProtocol(inc, packetheader, server);
                    break;

                case NetIncomingMessageType.StatusChanged:
                    Console.WriteLine(inc.SenderConnection + " status changed. " + inc.SenderConnection.Status);
                    if (inc.SenderConnection.Status == NetConnectionStatus.Disconnected)
                    {
                        Console.WriteLine("Player: {0} has disconnected",
                            Players[inc.SenderConnection.RemoteUniqueIdentifier].Name);
                        Players.Remove(inc.SenderConnection.RemoteUniqueIdentifier);
                    }
                    break;

                case NetIncomingMessageType.DiscoveryRequest:
                    NetOutgoingMessage discovermsg = server.CreateMessage();
                    discovermsg.Write("Hey I just met you, I'm a server, so address me maybe");
                    Console.WriteLine(@"Auto Discovery Request");
                    server.SendDiscoveryResponse(discovermsg, inc.SenderEndPoint);
                    break;

                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.ErrorMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.VerboseDebugMessage:
                    Console.WriteLine(@"---Debug---");
                    Console.WriteLine(inc.ReadString());
                    Console.WriteLine(@"---End---");
                    break;
            }
        }
开发者ID:JamieH,项目名称:Pictionary,代码行数:60,代码来源:Program.cs


示例2: UpdateAllResources

 public void UpdateAllResources(NetServer server)
 {
     foreach (Player item in this.Players)
     {
         this.UpdateResource(server, item);
     }
 }
开发者ID:Vbitz,项目名称:CodeCrusade,代码行数:7,代码来源:Game.cs


示例3: NetworkManager

 public NetworkManager(int Port, string AppID)
 {
     Config = new NetPeerConfiguration(AppID);
     Config.Port = Port;
     Server = new NetServer(Config);
     Server.Start();
 }
开发者ID:fusspawn,项目名称:sobriety,代码行数:7,代码来源:NetworkManager.cs


示例4: NetManager

 public NetManager()
 {
     NetPeerConfiguration config = new NetPeerConfiguration("Jape.Moose");
     config.Port = 10900;
     config.LocalAddress = NetUtility.Resolve("localhost");
     m_server = new NetServer(config);
 }
开发者ID:Johanw123,项目名称:MonoPlatformerGame,代码行数:7,代码来源:NetManager.cs


示例5: Process

        public static void Process(NetServer server, NetBuffer buffer, NetConnection sender)
        {
            Config config = Config.Instance;

            List<NetConnection> connections = server.Connections;

            //Lets send that message onto any plugin clients
            foreach (NetConnection connection in connections)
            {
                if (config.Server.client_connections.ContainsKey(connection.RemoteEndpoint.ToString()))
                {
                    string client_type = (string)config.Server.client_connections[connection.RemoteEndpoint.ToString()];

                    if (client_type.ToLower() == "plugin")
                    {
                        string msg = buffer.ReadString();

                        Console.WriteLine("Slave: Data sent - " + msg);

                        NetBuffer slavebuf = server.CreateBuffer();

                        slavebuf.Write(msg);

                        server.SendMessage(slavebuf, connection, NetChannel.ReliableInOrder4);
                    }
                }
            }
        }
开发者ID:rcrowe,项目名称:ees_xplane,代码行数:28,代码来源:SlaveHandler.cs


示例6: Server

 public Server(int MaxConnections, int Port)
 {
     NetPeerConfiguration config = new NetPeerConfiguration("CozyAnywhere");
     config.MaximumConnections   = MaxConnections;
     config.Port                 = Port;
     server                      = new NetServer(config);
 }
开发者ID:shangshen,项目名称:cozy,代码行数:7,代码来源:ServerMain.cs


示例7: SetUpConnection

        public void SetUpConnection()
        {
            configuration = new NetPeerConfiguration("PingPong");

            configuration.EnableMessageType(NetIncomingMessageType.WarningMessage);
            configuration.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage);
            configuration.EnableMessageType(NetIncomingMessageType.ErrorMessage);
            configuration.EnableMessageType(NetIncomingMessageType.Error);
            configuration.EnableMessageType(NetIncomingMessageType.DebugMessage);
            configuration.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            configuration.EnableMessageType(NetIncomingMessageType.Data);

            switch (networkRole)
            {
                case GamerNetworkType.Client:
                    Client = new NetClient(configuration);
                    Client.Start();
                    Client.Connect(new IPEndPoint(NetUtility.Resolve(IP), Convert.ToInt32(Port)));
                    break;
                case GamerNetworkType.Server:
                    configuration.Port = Convert.ToInt32(Port);
                    Server = new NetServer(configuration);
                    Server.Start();
                    break;
                default:
                    throw new ArgumentException("Network type was not set");
            }
        }
开发者ID:ICanHaz,项目名称:Super-Ping-Pong,代码行数:28,代码来源:NetworkManager.cs


示例8: ServerHandleConnections

        /// <summary>
        ///     Метод для работып отока обработчика входящих новых соединений с сервером
        /// </summary>
        private static void ServerHandleConnections(object obj) {
            Log.Print("Starting Listen connections", LogType.Network);

            var config = new NetPeerConfiguration(Settings.GameIdentifier) {
                Port = Settings.Port,
                MaximumConnections = Settings.MaxConnections,
                SendBufferSize = 400000,
                UseMessageRecycling = true,
            };

            /* Получаем возможные адреса сервера */
            Log.Print("Server IP's:", LogType.Network);
            Log.Print("-------", LogType.Network);
            IPAddress[] ipList = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in ipList) {
                if (ip.AddressFamily == AddressFamily.InterNetwork) {
                    Log.Print(ip.ToString(), LogType.Network);
                }
            }
            Log.Print("-------", LogType.Network);

            _server = new NetServer(config);
            _server.Start();

            // Запускаем обработчик пакетов
            StartProcessIncomingMessages();
        }
开发者ID:Insality,项目名称:essence-of-shadows,代码行数:30,代码来源:Server.cs


示例9: Main

        static void Main(string[] args)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            Console.WriteLine("This is the server");
            Players = new List<Player>();
            Config = new NetPeerConfiguration("MyGame");
            Console.WriteLine("Server configuration created.");
            Config.Port = 7777;
            Config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            Server = new NetServer(Config);
            Console.WriteLine("Server socket initialized");
            Server.RegisterReceivedCallback(new SendOrPostCallback(ReceiveData));
            Server.Start();
            Console.WriteLine("Server started");

            new Thread(new ThreadStart(delegate
                {
                    string input;

                    while ((input = Console.ReadLine()) != null)
                    {
                        Console.WriteLine("New Input.");
                        string[] prms = input.Split(' ');

                        switch (prms[0])
                        {
                            //No commands on server as of now
                        }
                    }
                })).Start();
        }
开发者ID:ChosunOne,项目名称:Network_Test_1,代码行数:31,代码来源:Program.cs


示例10: fireDataRecieved

 public void fireDataRecieved(NetServer server, NetBuffer buffer, NetConnection sender)
 {
     if (DataRecieved != null)
     {
         DataRecieved(server, buffer, sender);
     }
 }
开发者ID:rcrowe,项目名称:ees_xplane,代码行数:7,代码来源:NetworkEvents.cs


示例11: fireStatusChanged

 public void fireStatusChanged(NetServer server, NetBuffer buffer, NetConnection sender)
 {
     if (StatusChanged != null)
     {
         StatusChanged(server, buffer, sender);
     }
 }
开发者ID:rcrowe,项目名称:ees_xplane,代码行数:7,代码来源:NetworkEvents.cs


示例12: MasterServer

        /// <summary>
        ///     Server constructor, starts the server and connects to all region servers.
        /// </summary>
        /// <remarks>
        ///     TODO: Make the config file be able to be in a different location. Load from command line.
        /// </remarks>
        public MasterServer()
        {
            //Load this region server's junk from xml
            XmlSerializer deserializer = new XmlSerializer(typeof(MasterConfig));
            MasterConfig masterconfig = (MasterConfig)deserializer.Deserialize(XmlReader.Create(@"C:\Users\Addie\Programming\Mobius\Mobius.Server.MasterServer\bin\Release\MasterData.xml"));
            //Start it with the name MobiusMasterServer, and let connection approvals be enabled
            var config = new NetPeerConfiguration(masterconfig.ServerName);
            config.Port = masterconfig.ServerPort;
            config.MaximumConnections = masterconfig.MaxConnections;
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            LidgrenServer = new NetServer(config);

            RegionServers = new Dictionary<ushort, NetClient>();
            foreach(RegionInfo info in masterconfig.RegionServers)
            {
                NetClient region = new NetClient(new NetPeerConfiguration(info.ServerName));
                region.Start();
                region.Connect(info.ServerIp, info.ServerPort);
                RegionServers.Add(info.RegionId, region);
            }

            //Initialize our data structures
            Users = new Dictionary<Guid, User>();
            UserIdToCharacters = new Dictionary<Guid, List<Character>>();
            //Start the server
            LidgrenServer.Start();
        }
开发者ID:addiem7c5,项目名称:Old-Stability-Stuff,代码行数:33,代码来源:MasterServer.cs


示例13: ProcessPacket

        private static bool ProcessPacket(NetServer server, int id, NetIncomingMessage msg)
        {
            if (id == MsgId.AccountReg)
            {
                OnProcessAccountReg(server, id, msg);
                return true;
            }
            else if (id == MsgId.AgarLogin)
            {
                OnProcessLogin(server, id, msg);
                return true;
            }
            else if (id == MsgId.AgarPlayInfo)
            {
                return OnProcessPlayerInfo(server, id, msg);
            }
            else if (id == MsgId.AgarBorn)
            {
                OnProcessBorn(server, id, msg);
                return true;
            }
            else if (id == MsgId.HappyPlayerLogin)
            {
                OnProcessHappyLogin(server, id, msg);
                return true;
            }
            else if(id == MsgId.HappyPlayerMove)
            {
                return OnProgressHappyPlayerMove(server, id, msg);
            }

            return false;
        }
开发者ID:xxy1991,项目名称:cozy,代码行数:33,代码来源:ServerOperat.cs


示例14: TrackingServer

 public TrackingServer(int port, string applicationName)
 {
   NetPeerConfiguration config = new NetPeerConfiguration(applicationName);
   config.Port = port;
   netServer = new NetServer(config);
   Console.WriteLine("Server " + applicationName + " started succesfully");
 }
开发者ID:vs-team,项目名称:casanova-mk2,代码行数:7,代码来源:TrackingServer.cs


示例15: NetworkServer

 /// <summary>
 /// Initializes a new instance of the <see cref="NetworkServer" /> class.
 /// </summary>
 /// <param name="applicationIdentifier">The application identifier.</param>
 /// <param name="port">The port.</param>
 public NetworkServer(string applicationIdentifier, int port)
 {
     var config = new NetPeerConfiguration(applicationIdentifier);
     config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
     config.Port = port;
     this.server = new NetServer(config);
 }
开发者ID:WaveEngine,项目名称:Extensions,代码行数:12,代码来源:NetworkServer.cs


示例16: SetupServer

        public void SetupServer(string gameName, int port = 14242, int maxConnections = 20)
        {
            // Create new instance of configs. Parameter is "application Id". It has to be same on client and server.
            var config = new NetPeerConfiguration(gameName) { Port = port, MaximumConnections = maxConnections };
            _heroList = new List<LoginInfo>();
            // Set server port

            // Max client amount
            // Enable New messagetype. Explained later
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

            // Create new server based on the configs just defined
            _gameServer = new NetServer(config);

            // Start it
            _gameServer.Start();

            // Eh..
            Console.WriteLine("Server Started");

            // Object that can be used to store and read messages
            NetIncomingMessage inc;
            _serverThread = new Thread(() =>
            {
                while (true)
                {
                    ServerLoop();
                }
            });
            _serverThread.IsBackground = true;
            _serverThread.Start();
        }
开发者ID:Choochoo,项目名称:Ship,代码行数:32,代码来源:Host.cs


示例17: Server

        public Server()
        {
            ConnectedPlayers = new List<ConnectedPlayer>();

            _configuration = new NetPeerConfiguration("space_fight");
            server = new NetServer(_configuration);
        }
开发者ID:dvdking,项目名称:SpaceFight,代码行数:7,代码来源:Program.cs


示例18: GameServer

        public GameServer()
        {
            /* Load Resources */
            Console.WriteLine("Loading Resources...");
            Resources = new ResourceManager();
            Resources.Load();

            /* Setting Up Server */
            Console.WriteLine("Starting Up Server...");
            //Package.RecompilePackages();
            //CodeManager StartUp = Package.GetPackage(Game.ServerInfo.StartupPackage).CodeManager;
            //StartUp.RunMain();
            //Game.World.Chunks.ClearWorldGen();
            //Game.World.Chunks.AddWorldGens(StartUp.GetWorldGens());
            Game.World.ClearWorldGen();
            List<WorldGenerator> temp = new List<WorldGenerator>();
            temp.Add(new WorldGenerator());
            Game.World.AddWorldGen(temp);

            /* Listen for Clients */
            NetPeerConfiguration Configuration = new NetPeerConfiguration("FantasyScape");
            Configuration.Port = 54987;
            Configuration.MaximumConnections = 20;
            Server = new NetServer(Configuration);
            Server.Start();
            Message.RegisterServer(Server);

            UpdateTimer = new Stopwatch();
            UpdateTimer.Start();

            Console.WriteLine("Ready!");
        }
开发者ID:CloneDeath,项目名称:FantasyScape,代码行数:32,代码来源:GameServer.cs


示例19: SendMessage

 private static void SendMessage(NetServer server, MsgBase msg, NetConnection conn)
 {
     NetOutgoingMessage om = server.CreateMessage();
     om.Write(msg.Id);
     msg.W(om);
     server.SendMessage(om, conn, NetDeliveryMethod.Unreliable, 0);
 }
开发者ID:xxy1991,项目名称:cozy,代码行数:7,代码来源:ServerOperat.cs


示例20: RegionServer

        /// <summary>
        ///     Constructor taking the path to the configuration file. 
        ///     Starts the lidgren server to start listening for connections, and 
        ///     initializes all data structres and such.
        /// </summary>
        /// <param name="configpath"></param>
        public RegionServer(string configpath)
        {
            //Load this region server's junk from xml
            XmlSerializer deserializer = new XmlSerializer(typeof(RegionConfig));
            RegionConfig regionconfig = (RegionConfig)deserializer.Deserialize(XmlReader.Create(configpath));

            //Create the server
            var config = new NetPeerConfiguration(regionconfig.ServerName);
            config.Port = regionconfig.ServerPort;
            LidgrenServer = new NetServer(config);
            LidgrenServer.Start();

            //Initizlie our data structures
            Characters = new Dictionary<Guid, Character>();
            UserIdToMasterServer = new Dictionary<Guid, NetConnection>();
            TeleportEnters = new List<TeleportEnter>(regionconfig.TeleportEnters);
            TeleportExits = new List<TeleportExit>(regionconfig.TeleportExits);
            ItemSpawns = new List<ItemSpawn>(regionconfig.ItemSpawns);
            ItemSpawnIdGenerator = new UniqueId();
            ItemSpawnsWaitingForSpawn = new Dictionary<ItemSpawn, DateTime>();

            foreach(ItemSpawn spawn in ItemSpawns)
                ItemSpawnIdGenerator.RegisterId(spawn.Id);

            RegionId = regionconfig.RegionId;
        }
开发者ID:addiem7c5,项目名称:Old-Stability-Stuff,代码行数:32,代码来源:RegionServer.cs



注:本文中的Lidgren.Network.NetServer类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# LilyPath.Pen类代码示例发布时间:2022-05-26
下一篇:
C# Network.NetPeerConfiguration类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap