当前位置: 首页>>代码示例>>C#>>正文


C# NetServer.Shutdown方法代码示例

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


在下文中一共展示了NetServer.Shutdown方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			MainForm = new Form1();

			NetPeerConfiguration config = new NetPeerConfiguration("durable");
			config.Port = 14242;
			config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
			config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
			config.EnableUPnP = true;
			Server = new NetServer(config);
			Server.Start();

			// attempt upnp port forwarding
			Server.UPnP.ForwardPort(14242, "Durable sample test");

			m_expectedReliableOrdered = new uint[3];
			m_reliableOrderedCorrect = new int[3];
			m_reliableOrderedErrors = new int[3];

			m_expectedSequenced = new uint[3];
			m_sequencedCorrect = new int[3];
			m_sequencedErrors = new int[3];

			Application.Idle += new EventHandler(AppLoop);
			Application.Run(MainForm);

			Server.Shutdown("App exiting");
		}
开发者ID:pr0gramm3r1,项目名称:AngryTanks,代码行数:30,代码来源:Program.cs

示例2: Main

		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			s_form = new Form1();

			NetPeerConfiguration config = new NetPeerConfiguration("filestream");
			config.Port = 14242;
			s_server = new NetServer(config);

			Application.Idle += new EventHandler(AppLoop);
			Application.Run(s_form);

			s_server.Shutdown("Application exiting");
		}
开发者ID:pr0gramm3r1,项目名称:AngryTanks,代码行数:15,代码来源:Program.cs

示例3: Main

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            s_mainForm = new Form1();

            NetConfiguration config = new NetConfiguration("OoBSample");
            config.MaxConnections = 0; // we accept only OoB data
            config.Port = 14242;
            s_server = new NetServer(config);
            s_server.SetMessageTypeEnabled(NetMessageType.OutOfBandData, true);
            s_server.Start();

            s_readBuffer = s_server.CreateBuffer();

            Application.Idle += new EventHandler(OnAppIdle);
            Application.Run(s_mainForm);

            s_server.Shutdown("Bye");
        }
开发者ID:JeffM2501,项目名称:HackSharp,代码行数:20,代码来源:Program.cs

示例4: Main

		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			s_mainForm = new Form1();

			NetConfiguration config = new NetConfiguration("stress");
			config.Port = 14242;
			config.MaxConnections = 32;
			s_server = new NetServer(config);

			s_server.SimulatedMinimumLatency = 0.1f;
			s_server.SimulatedLatencyVariance = 0.05f;
//			s_server.SimulatedLoss = 0.1f;
//			s_server.SimulatedDuplicates = 0.05f;

			s_readBuffer = s_server.CreateBuffer();

			Application.Idle += new EventHandler(OnAppIdle);
			Application.Run(s_mainForm);

			s_server.Shutdown("Application exiting");
		}
开发者ID:marvel54,项目名称:lidgren-network,代码行数:23,代码来源:Program.cs

示例5: Main


//.........这里部分代码省略.........
								buf.Write((int)52, 7);
								buf.Write("Hallon");

								client.SendMessage(buf, NetChannel.ReliableInOrder1, new NetBuffer("kokos"));
							}

							if (client.Status == NetConnectionStatus.Disconnected)
								end = NetTime.Now + 1.0; // end in one second

							break;
						case NetMessageType.Receipt:
							events.Add("CReceipt " + clientBuffer.ReadString());
							break;
						case NetMessageType.ConnectionRejected:
						case NetMessageType.BadMessageReceived:
							throw new Exception("Failed: " + nmt);
						case NetMessageType.DebugMessage:
							// silently ignore
							break;
						default:
							// ignore
							Console.WriteLine("Ignored: " + nmt);
							break;
					}
				}

				//
				// server
				//
				if (server.ReadMessage(serverBuffer, out nmt, out sender))
				{
					switch (nmt)
					{
						case NetMessageType.StatusChanged:
							events.Add("SStatus " + sender.Status);
							Console.WriteLine("Server: " + sender.Status + " (" + serverBuffer.ReadString() + ")");
							break;
						case NetMessageType.ConnectionRejected:
						case NetMessageType.BadMessageReceived:
							throw new Exception("Failed: " + nmt);
						case NetMessageType.Data:
							events.Add("DataRec " + serverBuffer.LengthBits);
							bool shouldBeTrue = serverBuffer.ReadBoolean();
							int shouldBeFifthTwo = serverBuffer.ReadInt32(7);
							string shouldBeHallon = serverBuffer.ReadString();

							if (shouldBeTrue != true ||
								shouldBeFifthTwo != 52 ||
								shouldBeHallon != "Hallon")
								throw new Exception("Bad data transmission");

							disconnect = now + 1.0;
							break;
						case NetMessageType.DebugMessage:
							// silently ignore
							break;
						default:
							// ignore
							Console.WriteLine("Ignored: " + nmt);
							break;
					}
				}

				if (now > disconnect)
				{
					server.Connections[0].Disconnect("Bye", 0.1f);
					disconnect = double.MaxValue;
				}
			}

			// verify events
			string[] expected = new string[] {
				"CStatus Connecting",
				"SStatus Connecting",
				"CStatus Connected",
				"SStatus Connected",
				"DataRec 64",
				"CReceipt kokos",
				"SStatus Disconnecting",
				"CStatus Disconnecting",
				"SStatus Disconnected",
				"CStatus Disconnected"
			};

			if (events.Count != expected.Length)
				throw new Exception("Mismatch in events count! Expected " + expected.Length + ", got " + events.Count);

			for(int i=0;i<expected.Length;i++)
			{
				if (events[i] != expected[i])
					throw new Exception("Event " + i + " (" + expected[i] + ") mismatched!");
			}

			Console.WriteLine("All tests successful");

			Console.ReadKey();

			server.Shutdown("App exiting");
			client.Shutdown("App exiting");
		}
开发者ID:marvel54,项目名称:lidgren-network,代码行数:101,代码来源:Program.cs

示例6: Run

        public void Run()
        {
            bool running = true;

            Console.WriteLine("Backup Remote");
            Console.Write("Master key: ");

            string key = "";
            ConsoleKeyInfo info;

            do
            {
                info = Console.ReadKey(true);

                if (info.Key != ConsoleKey.Backspace && info.Key != ConsoleKey.Enter)
                {
                    key += info.KeyChar;
                    Console.Write("*");
                }
                else if (info.Key == ConsoleKey.Backspace && key.Length > 0)
                {
                    key = key.Substring(0, key.Length - 1);
                    Console.Write("\b \b");
                }
            }
            while (info.Key != ConsoleKey.Enter);

            keyHash = GetHash(key);
            key = string.Empty;

            Console.WriteLine();
            Console.Write("Backup directory: ");

            backupDir = Console.ReadLine();

            if (!Directory.Exists(backupDir))
            {
                Console.WriteLine("Directory doesn't exist");
                return;
            }

            Console.WriteLine("Initializing...");

            Command.Register("close", a => running = false);
            Command.Register("manifest", a =>
            {
                if (a.Length == 0)
                {
                    Console.WriteLine(targetManager.GetManifestJSON());
                    return;
                }

                if (a[0] == "save")
                {
                    Console.WriteLine("Forced manifest save");
                    targetManager.SaveManifest();
                }
            });

            targetManager = new TargetManager(backupDir);

            NetPeerConfiguration cfg = new NetPeerConfiguration("BackupUtil");
            cfg.Port = 6969;

            cfg.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            cfg.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);

            SynchronizationContext sync = new SynchronizationContext();
            SynchronizationContext.SetSynchronizationContext(sync);

            server = new NetServer(cfg);
            server.RegisterReceivedCallback(new SendOrPostCallback(MessageReceived), sync);
            server.Start();

            Console.WriteLine("Initialized");

            string line;
            while (running)
            {
                line = Console.ReadLine();

                string[] lineArgs = line.Split(' ');
                if (!Command.Run(lineArgs[0], lineArgs.Skip(1).ToArray()))
                    Console.WriteLine("Invalid command");
            }

            Console.WriteLine("Closing...");

            server.Shutdown("bye"); // TODO: figure out why client doesn't receive the message that the server is shut down
        }
开发者ID:Spanfile,项目名称:BackupUtil,代码行数:90,代码来源:Remote.cs

示例7: Main


//.........这里部分代码省略.........
                                        npcs[(int)damage.PlayerId].Life -= 1;
                                        if (npcs[(int)damage.PlayerId].Life <= 0)
                                            npcs.RemoveAt((int)damage.PlayerId);
                                    }
                                    break;
                            }
                            break;
                    }

                    // send position updates 30 times per second
                    double now = NetTime.Now;
                    if (now > nextSendUpdates)
                    {
                        foreach (var position in positions.Values)
                        {
                            foreach (var npc in npcs)
                            {
                                float velX = position.X - npc.X;
                                float velY = position.Y - npc.Y;
                                float distance = (float)Math.Sqrt(Math.Pow(velX, 2) + Math.Pow(velY, 2));
                                if (distance < 300 && distance > 30)
                                {
                                    velX /= distance;
                                    velY /= distance;

                                    npc.X += (int)(velX * npc.Speed);
                                    npc.Y += (int)(velY * npc.Speed);

                                    NetOutgoingMessage om2 = server.CreateMessage();
                                    om2.Write((byte)MessageRouts.MoveNpc);
                                    om2.Write((byte)npcs.IndexOf(npc));
                                    om2.Write((int)npc.X);
                                    om2.Write((int)npc.Y);

                                    foreach (NetConnection player in server.Connections)
                                        server.SendMessage(om2, player, NetDeliveryMethod.ReliableUnordered);
                                }

                            }
                        }

                        foreach (NetConnection player in server.Connections)
                        {
                            foreach (var damagePair in damages)
                            {
                                if (damagePair.Key != player)
                                {
                                    foreach (var damage in damagePair.Value)
                                    {
                                        NetOutgoingMessage om2 = server.CreateMessage();
                                        om2.Write((byte)MessageRouts.Fire);
                                        om2.Write(damagePair.Key.RemoteUniqueIdentifier);
                                        om2.Write(damage.PlayerId);
                                        om2.Write(damage.WeaponId);
                                        om2.Write(damage.Angle);
                                        om2.Write(damage.X);
                                        om2.Write(damage.Y);

                                        server.SendMessage(om2, player, NetDeliveryMethod.ReliableUnordered);
                                    }
                                }
                            }

                            foreach (NetConnection otherPlayer in server.Connections)
                            {
                                if (player != otherPlayer)
                                {
                                    NetOutgoingMessage om = server.CreateMessage();

                                    if (positions.ContainsKey(otherPlayer))
                                    {
                                        om.Write((byte)MessageRouts.Position);
                                        om.Write(otherPlayer.RemoteUniqueIdentifier);
                                        om.Write(positions[otherPlayer].X);
                                        om.Write(positions[otherPlayer].Y);
                                        om.Write(positions[otherPlayer].Angle);
                                        om.Write(positions[otherPlayer].IsShooting);
                                        om.Write(positions[otherPlayer].IsHuman);
                                        server.SendMessage(om, player, NetDeliveryMethod.Unreliable);
                                    }

                                    // send message
                                }
                            }
                        }

                        foreach (var damageList in damages.Values)
                            damageList.Clear();

                        // schedule next update
                        nextSendUpdates += (1.0 / 30.0);
                    }
                }

                // sleep to allow other processes to run smoothly
                Thread.Sleep(1);
            }

            server.Shutdown("app exiting");
        }
开发者ID:wallymathieu,项目名称:WindowsGame9,代码行数:101,代码来源:XnaServer.cs

示例8: Main


//.........这里部分代码省略.........

                                case (byte)PacketTypes.DELETEENEMY:
                                    int enemyDead = msg.ReadInt16();
                                    if (enemies.Count > 0 && finishWritingLevel == true)
                                        enemies[enemyDead].isDead = true;
                                    break;

                                case (byte)PacketTypes.GETSERVERENEMYPOSITIONS:
                                    msgOut = server.CreateMessage();

                                    msgOut.Write((byte)PacketTypes.SENDENEMYPOSITIONS);

                                    for (int i = 0; i < enemies.Count; i++)
                                    {

                                        msgOut.Write((byte)enemies[i].state);
                                        msgOut.Write((byte)enemies[i].lastState);
                                        msgOut.Write((bool)enemies[i].isDead);
                                        msgOut.Write((float)enemies[i].x);
                                        msgOut.Write((float)enemies[i].y);
                                    }

                                    server.SendMessage(msgOut, msg.SenderConnection, NetDeliveryMethod.ReliableOrdered);

                                    break;

                                case (byte)PacketTypes.GETSERVERLEVEL:
                                    msgOut = server.CreateMessage();

                                    msgOut.Write((byte)PacketTypes.GETLEVEL);
                                    msgOut.Write((short)level);
                                    msgOut.Write((short)enemies.Count);

                                    for (int i = 0; i < enemies.Count; i++)
                                    {
                                        msgOut.Write((byte)enemies[i].state);
                                        msgOut.Write((byte)enemies[i].lastState);
                                        msgOut.Write((short)enemies[i].health);
                                        msgOut.Write((bool)enemies[i].isDead);
                                        msgOut.Write((float)enemies[i].x);
                                        msgOut.Write((float)enemies[i].y);

                                    }
                                    server.SendMessage(msgOut, msg.SenderConnection, NetDeliveryMethod.ReliableOrdered);
                                    break;

                                case (byte)PacketTypes.GETENEMYTARGETPLAYER:
                                    SetEnemyTarget();
                                    SendToAllPlayerEnemyTarget();

                                    break;

                                case (byte)PacketTypes.GAMEOVER:
                                    gameOver = true;
                                    break;
                            }
                            break;
                    }

                }

                double now = NetTime.Now;
                if (now > nextSendUpdates)
                {
                    // Yes, it's time to send position updates

                    // for each player...
                    for (int i = 0; i < server.Connections.Count; i++)
                    {
                        NetConnection player = server.Connections[i] as NetConnection;
                        // ... send information about every other player (actually including self)
                        for (int j = 0; j < multiplayerPlayers.Count; j++)
                        {
                            // send position update about 'otherPlayer' to 'player'
                            NetOutgoingMessage om = server.CreateMessage();

                            // write who this position is for
                            om.Write((byte)PacketTypes.UPDATEPLAYERS);
                            om.Write((long)multiplayerPlayers[j].id);
                            om.Write((byte)multiplayerPlayers[j].state);
                            om.Write((byte)multiplayerPlayers[j].lastState);
                            om.Write((int)multiplayerPlayers[j].health);
                            om.Write((bool)multiplayerPlayers[j].isDead);
                            om.Write((float)multiplayerPlayers[j].x);
                            om.Write((float)multiplayerPlayers[j].y);

                            // send message
                            server.SendMessage(om, player, NetDeliveryMethod.Unreliable);
                        }

                    }
                    // schedule next update
                    nextSendUpdates += (1.0 / 60.0);
                }
                // sleep to allow other processes to run smoothly
                Thread.Sleep(1);
            }

            server.Shutdown("app exiting");
        }
开发者ID:wuwenhuang,项目名称:RobotContra,代码行数:101,代码来源:Program.cs

示例9: StartServer

        private static void StartServer()
        {
            // create a configuration for the server
            NetConfiguration config = new NetConfiguration("EES");
            config.MaxConnections = 128;
            config.Port = 14242;

            // create server and start listening for connections
            NetServer server = new NetServer(config);
            server.SetMessageTypeEnabled(NetMessageType.DebugMessage, false);
            server.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true);
            server.Start();

            // create a buffer to read data into
            NetBuffer buffer = server.CreateBuffer();

            // keep running until the user presses a key
            Console.WriteLine("Press ESC to quit server");
            bool keepRunning = true;
            while (keepRunning)
            {
                NetMessageType type;
                NetConnection sender;

                // check if any messages has been received
                while (server.ReadMessage(buffer, out type, out sender))
                {
                    switch (type)
                    {
                        case NetMessageType.DebugMessage:
                            netevent.fireDebugMessage(buffer.ReadString());
                            break;

                        case NetMessageType.ConnectionApproval:
                            netevent.fireClientApproval(server, buffer, sender);
                            break;

                        case NetMessageType.StatusChanged:
                            netevent.fireStatusChanged(server, buffer, sender);
                            break;

                        case NetMessageType.Data:
                            netevent.fireDataRecieved(server, buffer, sender);
                            break;
                    }
                }

                // User pressed ESC?
                while (Console.KeyAvailable)
                {
                    ConsoleKeyInfo info = Console.ReadKey();

                    if (info.Key == ConsoleKey.Escape)
                    {
                        keepRunning = false;
                    }
                    else if (info.Key == ConsoleKey.I)
                    {
                        //Create line
                        Console.WriteLine("");

                        //Get config
                        Config server_config = Config.Instance;

                        foreach (DictionaryEntry entry in server_config.Server.client_connections)
                        {
                            Console.WriteLine("Client: '" + entry.Value + "' from: " + entry.Key);
                        }
                    }
                }

                Thread.Sleep(1);
            }

            server.Shutdown("Server exiting");
        }
开发者ID:rcrowe,项目名称:ees_xplane,代码行数:76,代码来源:Program.cs

示例10: Start


//.........这里部分代码省略.........

			// run until escape is pressed
			//while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape)
			while(true)
            {
				NetIncomingMessage msg;
				while ((msg = server.ReadMessage()) != null)
				{
					switch (msg.MessageType)
					{
						case NetIncomingMessageType.DiscoveryRequest:
							//
							// Server received a discovery request from a client; send a discovery response (with no extra data attached)
							//
							server.SendDiscoveryResponse(null, msg.SenderEndpoint);
							break;
						case NetIncomingMessageType.VerboseDebugMessage:
						case NetIncomingMessageType.DebugMessage:
						case NetIncomingMessageType.WarningMessage:
						case NetIncomingMessageType.ErrorMessage:
							//
							// Just print diagnostic messages to console
							//
							Console.WriteLine(msg.ReadString());
							break;
						case NetIncomingMessageType.StatusChanged:
							NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
							if (status == NetConnectionStatus.Connected)
							{
								//
								// A new player just connected!
								//
								Console.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected!");

								// randomize his position and store in connection tag
								msg.SenderConnection.Tag = new int[] {
									NetRandom.Instance.Next(10, 100),
									NetRandom.Instance.Next(10, 100)
								};
							}

							break;
						case NetIncomingMessageType.Data:
							//
							// The client sent input to the server
							//
							int xinput = msg.ReadInt32();
							int yinput = msg.ReadInt32();

							int[] pos = msg.SenderConnection.Tag as int[];

							// fancy movement logic goes here; we just append input to position
							pos[0] += xinput;
							pos[1] += yinput;
							break;
					}

					//
					// send position updates 30 times per second
					//
					double now = NetTime.Now;
					if (now > nextSendUpdates)
					{
						// Yes, it's time to send position updates

						// for each player...
						foreach (NetConnection player in server.Connections)
						{
							// ... send information about every other player (actually including self)
							foreach (NetConnection otherPlayer in server.Connections)
							{
								// send position update about 'otherPlayer' to 'player'
								NetOutgoingMessage om = server.CreateMessage();

								// write who this position is for
								om.Write(otherPlayer.RemoteUniqueIdentifier);

								if (otherPlayer.Tag == null)
									otherPlayer.Tag = new int[2];

								int[] pos = otherPlayer.Tag as int[];
								om.Write(pos[0]);
								om.Write(pos[1]);

								// send message
								server.SendMessage(om, player, NetDeliveryMethod.Unreliable);
							}
						}

						// schedule next update
						nextSendUpdates += (1.0 / 30.0);
					}
				}

				// sleep to allow other processes to run smoothly
				Thread.Sleep(1);
			}

			server.Shutdown("app exiting");
		}
开发者ID:Dahie,项目名称:September-1983,代码行数:101,代码来源:ProgramServer.cs

示例11: ServerTaskFunc


//.........这里部分代码省略.........
			//var maxElapsedTime = TimeSpan.FromMilliseconds(1000);
			//var previousTicks = (long)0;

			//
			//	configure & start server :
			//
			try {

				server.Start();

				//
				//	start game specific stuff :
				//
				atoms	=	new AtomCollection();
				LoadContent( map );
				atoms.Lock();

				//
				//	invoke post-start command :
				//
				if (postCommand!=null) {
					Game.Invoker.Push( postCommand );
				}


				//	Timer and fixed timestep stuff :
				//	http://gafferongames.com/game-physics/fix-your-timestep/
				var accumulator	=	TimeSpan.Zero;
				var stopwatch	=	new Stopwatch();
				stopwatch.Start();
				var currentTime	=	stopwatch.Elapsed;
				var time		=	stopwatch.Elapsed;

				//
				//	server loop :
				//	
				while ( !killToken.IsCancellationRequested ) {

				_retryTick:
					var targetDelta	=	TimeSpan.FromTicks( (long)(10000000 / TargetFrameRate) );
					var newTime		=	stopwatch.Elapsed;
					var frameTime	=	newTime - currentTime;
					currentTime		=	newTime;

					accumulator +=	 frameTime;

					if ( accumulator < targetDelta ) {
						Thread.Sleep(1);
						goto _retryTick;
					}

					while ( accumulator > targetDelta ) {

						//var svTime = new GameTime( time, targetDelta );
						var svTime = new GameTime( serverFrames, time, targetDelta );
						serverFrames++;

						//
						//	Do actual server stuff :
						//	
						UpdateNetworkAndLogic( svTime, server, snapshotQueue );

						accumulator	-= targetDelta;
						time		+= targetDelta;
					}
				}

				foreach ( var conn in server.Connections ) {
					conn.Disconnect("Server disconnected");
				}

			} catch ( Exception e ) {
				Log.PrintException( e, "Server error: {0}", e.Message );

				foreach ( var conn in server.Connections ) {
					conn.Disconnect(string.Format("Server error: {0}", e.Message));
				}

			} finally {

				//
				//	kill game specific stuff :
				//	try...catch???
				//
				UnloadContent();

				//
				//	shutdown connection :
				//
				server.Shutdown("Server shutdown");
				Log.Message("SV: Shutdown");

				notifications	=	null;

				killToken	=	null;
				serverTask	=	null;
				server		=	null;
				pings		=	null;
			}
		}
开发者ID:demiurghg,项目名称:FusionEngine,代码行数:101,代码来源:GameServer.Internal.cs

示例12: Main

        static void Main(string[] args)
        {
            Console.WriteLine("Akanonda Server");
            Console.WriteLine("---------------");

            // NetServer START
            NetPeerConfiguration netconfig = new NetPeerConfiguration("game");
            netconfig.MaximumConnections = settings.MaxConnections;
            netconfig.Port = settings.GamePort;
            netserver = new NetServer(netconfig);

            NetPeerConfiguration config = new NetPeerConfiguration("chat");
            config.MaximumConnections = 100;
            config.Port = settings.ChatPort;
            chatServer = new NetServer(config);

            SurvivalTimer = new System.Timers.Timer();
            SurvivalTimer.Interval = 1000;
            SurvivalTimer.Elapsed += new ElapsedEventHandler(gameSecondTick);
            SurvivalTimer.Start();

            if (SynchronizationContext.Current == null)
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            netserver.RegisterReceivedCallback(new SendOrPostCallback(ReceiveData));

            netserver.Start();
            StartChat();

            game = Game.Instance;

            gameSpeedTimer = new System.Timers.Timer(settings.GameSpeed);
            gameSpeedTimer.Elapsed += new ElapsedEventHandler(gameSpeedTimer_Elapsed);
            gameSpeedTimer.Enabled = true;

            Console.Write("Command: ");
            while (true)
            {
                string input = Console.ReadLine();
                switch (input)
                {
                    case "start":
                        break;
                    case "status":
                        Console.WriteLine(netserver.ConnectionsCount);
                        break;
                    case "exit":
                        netserver.Shutdown("Exit");
                        Environment.Exit(0);
                        break;
                    case "stop Chat":
                        StopChat();
                        Console.WriteLine("Chat stopped");
                        break;
                    case "start Chat":
                        StartChat();
                        Console.WriteLine("Chat started");
                        break;
                    case "kick Player":
                        Console.WriteLine("Enter Player name:");
                        string playerToKick = Console.ReadLine();
                        Player playerToFind = game.PLayerList.Find(item => item.name == playerToKick);
                        if (playerToFind != null)
                        {
                            game.addDeadRemoveLivingPlayer(playerToFind.guid);
                        }
                        break;
                    default:
                        Console.WriteLine("Command not found.");
                        break;
                }
                Console.Write("Command: ");
            }
        }
开发者ID:JueZ,项目名称:ITP,代码行数:74,代码来源:Program.cs

示例13: Main


//.........这里部分代码省略.........
                            {
                                case 0:
                                    com.Write((int)PlayerId.Green);
                                    com.Write((int)mapSeed); //Write map seed
                                    break;
                                case 1:
                                    com.Write((int)PlayerId.Red);
                                    com.Write((int)mapSeed); //Write map seed
                                    gameStatus = GameStatus.Receive;
                                    break;
                            }
                            server.SendDiscoveryResponse(com, msg.SenderEndpoint);
                            Console.WriteLine("Connect to: " + msg.SenderEndpoint);
                            break;
                        case NetIncomingMessageType.Data:
                            if (gameStatus == GameStatus.Receive)
                            {
                                //
                                // The client sent input to the server
                                //
                                IncomingMessageType imt = (IncomingMessageType)msg.ReadByte();
                                if (imt == IncomingMessageType.DataPlayerInfo)
                                {
                                    int wayPointCounter = msg.ReadInt32();

                                    List<PlayerInfo> wayPoints = new List<PlayerInfo>();
                                    for (int i = 1; i <= wayPointCounter; ++i)
                                    {
                                        Vector3 tempPos;
                                        tempPos.X = msg.ReadFloat();
                                        tempPos.Y = msg.ReadFloat();
                                        tempPos.Z = msg.ReadFloat();

                                        float tempOrientation;
                                        tempOrientation = msg.ReadFloat();

                                        PlayerInfo wayPoint = new PlayerInfo(tempPos, tempOrientation);
                                        wayPoints.Add(wayPoint);
                                    }
                                    playerInfoDict[msg.SenderEndpoint] = wayPoints;
                                    Console.WriteLine("Receive message from" + msg.SenderEndpoint);

                                    clientDoneCounter++;
                                    if (clientDoneCounter == 2)
                                        gameStatus = GameStatus.Sending;

                                }
                            }
                            break;
                    }

                    //
                    // send position updates 30 times per second
                    //
                    if (gameStatus == GameStatus.Sending)
                    {
                            // Yes, it's time to send position updates

                            // for each player...
                            foreach (NetConnection player in server.Connections)
                            {
                                if (!playerInfoDict.ContainsKey(player.RemoteEndpoint))
                                    playerInfoDict[player.RemoteEndpoint] = new List<PlayerInfo>();
                            }
                            foreach (NetConnection player in server.Connections)
                            {
                                //send information about every other player(not including self)
                                foreach (NetConnection otherPlayer in server.Connections)
                                {
                                    if (player.RemoteEndpoint == otherPlayer.RemoteEndpoint)
                                        continue;

                                    // send position update about 'otherPlayer' to 'player'
                                    NetOutgoingMessage om = server.CreateMessage();
                                    om.Write((byte)OutgoingMessageType.DataOtherPlayerInfo);

                                    om.Write(playerInfoDict[otherPlayer.RemoteEndpoint].Count);

                                    foreach (PlayerInfo playerInfo in playerInfoDict[otherPlayer.RemoteEndpoint])
                                    {
                                        om.Write(playerInfo.position.X);
                                        om.Write(playerInfo.position.Y);
                                        om.Write(playerInfo.position.Z);
                                        om.Write(playerInfo.orientation);
                                    }
                                    //send message
                                    server.SendMessage(om, player, NetDeliveryMethod.ReliableOrdered);
                                }

                            }

                            gameStatus = GameStatus.Receive;
                            clientDoneCounter = 0;

                        }
                }
            }

            server.Shutdown("server exiting");
        }
开发者ID:kobe1home,项目名称:Project_Origin,代码行数:101,代码来源:Program.cs

示例14: Main


//.........这里部分代码省略.........
                                connectedPlayers++;
                                Console.WriteLine(connectedPlayers + " players ingame");
                            };

                            if (status == NetConnectionStatus.Disconnected)
                            {
                                Console.WriteLine(msg.SenderConnection.RemoteUniqueIdentifier + " disconnected. (IP Address: " + msg.SenderEndpoint.Address + ")");
                                connectedPlayers--;
                                Console.WriteLine(connectedPlayers + " players ingame");
                            }


                            break;
                        case NetIncomingMessageType.Data:
                            //
                            // The client sent input to the server
                            //

                            dummyName = msg.ReadString();
                            if (!PlayerNames.ContainsKey(msg.SenderConnection.RemoteUniqueIdentifier))
                            {
                                  PlayerNames.Add(msg.SenderConnection.RemoteUniqueIdentifier, dummyName);
                            }
                          

                            // fancy movement logic goes here

                            var xinput = msg.ReadInt32();
                            var yinput = msg.ReadInt32();
                            var playerAngle = msg.ReadFloat();

                            var pos = msg.SenderConnection.Tag as float[];

                            if (pos != null)
                            {
                                pos[0] = xinput;
                                pos[1] = yinput;
                                pos[2] = playerAngle;
                            }


                            break;

                    }

                    //
                    // send position updates 60 times per second
                    //
                    var now = NetTime.Now;
                    if (now > nextSendUpdates)
                    {
                        // Yes, it's time to send position updates

                        // for each player...


                        foreach (var player in server.Connections)
                        {
                            // ... send information about every other player (actually including self)
                            foreach (var otherPlayer in server.Connections)
                            {
                                // send position update about 'otherPlayer' to 'player'
                                var om = server.CreateMessage();
                                if (otherPlayer != null)
                                {
                                    // write who this position is for
                                    om.Write(otherPlayer.RemoteUniqueIdentifier);
                                    if (PlayerNames.ContainsKey(otherPlayer.RemoteUniqueIdentifier))
                                    {
                                        om.Write(PlayerNames.Single(i => i.Key == otherPlayer.RemoteUniqueIdentifier).Value);
                                    }


                                    if (otherPlayer.Tag == null)
                                        otherPlayer.Tag = new float[3];

                                    var pos = otherPlayer.Tag as float[];

                                    om.Write(pos[0]);
                                    om.Write(pos[1]);
                                    om.Write(pos[2]);

                                    // send message
                                    server.SendMessage(om, player, NetDeliveryMethod.Unreliable);
                                }

                            }
                        }

                        // schedule next update
                        nextSendUpdates += (1.0 / 60.0);
                    }
                }

                // sleep to allow other processes to run smoothly
                Thread.Sleep(1);
            }
            Console.WriteLine("Server powering down..");
            server.Shutdown("bye");
        }
开发者ID:umutseven92,项目名称:Romero.Windows,代码行数:101,代码来源:Program.cs

示例15: Main

		static void Main(string[] args)
		{
			NetConfiguration config = new NetConfiguration("durable");
			config.MaxConnections = 128;
			config.Port = 14242;
			NetServer server = new NetServer(config);

			server.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true);
			server.SetMessageTypeEnabled(NetMessageType.DebugMessage, true);
			//server.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
			server.SetMessageTypeEnabled(NetMessageType.StatusChanged, true);

			server.SimulatedMinimumLatency = 0.05f;
			server.SimulatedLatencyVariance = 0.025f;
			server.SimulatedLoss = 0.03f;

			server.Start();

			FileStream fs = new FileStream("./serverlog.txt", FileMode.Create, FileAccess.Write, FileShare.Read);
			StreamWriter wrt = new StreamWriter(fs);
			Output(wrt, "Log started at " + DateTime.Now);
			wrt.Flush();

			NetBuffer buffer = server.CreateBuffer();

			int expected = 1;

			Console.WriteLine("Press any key to quit");
			while (!Console.KeyAvailable)
			{
				NetMessageType type;
				NetConnection sender;
				if (server.ReadMessage(buffer, out type, out sender))
				{
					switch (type)
					{
						case NetMessageType.StatusChanged:
							if (sender.RemoteHailData != null)
								Output(wrt, "New status: " + sender.Status + " (" + buffer.ReadString() + ") Remote hail is: " + Encoding.ASCII.GetString(sender.RemoteHailData));
							else
								Output(wrt, "New status: " + sender.Status + " (" + buffer.ReadString() + ") Remote hail hasn't arrived.");
							break;
						case NetMessageType.BadMessageReceived:
						case NetMessageType.ConnectionRejected:
						case NetMessageType.DebugMessage:
							//
							// All these types of messages all contain a single string in the buffer; display it
							//
							Output(wrt, buffer.ReadString());
							break;
						case NetMessageType.VerboseDebugMessage:
							wrt.WriteLine(buffer.ReadString()); // don't output to console
							break;
						case NetMessageType.ConnectionApproval:
							if (sender.RemoteHailData != null &&
								Encoding.ASCII.GetString(sender.RemoteHailData) == "Hail from client")
							{
								Output(wrt, "Hail ok!");
								sender.Approve(Encoding.ASCII.GetBytes("Hail from server"));
							}
							else
							{
								sender.Disapprove("Wrong hail!");
							}
							break;
						case NetMessageType.Data:
							string str = buffer.ReadString();

							// parse it
							int nr = Int32.Parse(str.Substring(9));

							if (nr != expected)
							{
								Output(wrt, "Warning! Expected " + expected + "; received " + nr + " str is ---" + str + "---");
							}
							else
							{
								expected++;
								Console.Title = "Server; received " + nr + " messages";
							}

							break;
						default:
							Output(wrt, "Unhandled: " + type + " " + buffer.ToString());
							break;
					}
				}
				Thread.Sleep(1);
			}

			// clean shutdown
			wrt.Close();
			server.Shutdown("Application exiting");
		}
开发者ID:zakvdm,项目名称:Frenetic,代码行数:94,代码来源:Program.cs


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