Пример #1
0
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			s_mainForm = new Form1();

			NetConfiguration config = new NetConfiguration("stress");
			config.ThrottleBytesPerSecond = 3500;

			s_client = new NetClient(config);

			// 100 ms simulated roundtrip latency
			s_client.SimulatedMinimumLatency = 0.1f;

			// ... + 0 to 50 ms
			s_client.SimulatedLatencyVariance = 0.05f;

			// 10% loss (!)
		//	s_client.SimulatedLoss = 0.1f;

			// 5% duplicated messages (!)
		//	s_client.SimulatedDuplicates = 0.05f;
			
			s_readBuffer = s_client.CreateBuffer();

			s_sentUntil = NetTime.Now;
			s_nextDisplay = NetTime.Now;
			
			Application.Idle += new EventHandler(OnAppIdle);
			Application.Run(s_mainForm);

			s_client.Shutdown("Application exiting");
		}
 /// <summary>
 /// Creates a new NetServer
 /// </summary>
 public NetServer(NetConfiguration config)
     : base(config)
 {
     m_connections      = new List <NetConnection>();
     m_connectionLookup = new uLink.Dictionary <NetworkEndPoint, NetConnection>();
     m_pendingLookup    = new uLink.Dictionary <NetworkEndPoint, NetConnection>();
 }
Пример #3
0
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			s_mainForm = new Form1();

			WriteToConsole("Type 'connect <host> <port>' to connect to another peer, or 'connect <port>' to connect to another localhost peer");

			NetConfiguration config = new NetConfiguration("p2pchat");
			config.MaxConnections = 256;
			s_peer = new NetPeer(config);
			//s_peer.VerboseLog = true;

			s_peer.SetMessageTypeEnabled(NetMessageType.ConnectionRejected | NetMessageType.BadMessageReceived | NetMessageType.VerboseDebugMessage, true);

			// start listening for incoming connections
			s_peer.Start();

			// create a buffer to read data into
			s_readBuffer = s_peer.CreateBuffer();

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

			s_peer.Shutdown("Application exiting");
		}
Пример #4
0
        protected NetBase(NetConfiguration config)
        {
            Debug.Assert(config != null, "Config must not be null");
            if (string.IsNullOrEmpty(config.ApplicationIdentifier))
            {
                throw new ArgumentException("Must set ApplicationIdentifier in NetConfiguration!");
            }
            m_config           = config;
            m_receiveBuffer    = new NetBuffer(config.ReceiveBufferSize);
            m_sendBuffer       = new NetBuffer(config.SendBufferSize);
            m_senderRemote     = (EndPoint) new IPEndPoint(IPAddress.Any, 0);
            m_statistics       = new NetBaseStatistics();
            m_receivedMessages = new NetQueue <IncomingNetMessage>(4);
            m_scratchBuffer    = new NetBuffer(32);
            m_bindLock         = new object();
            m_discovery        = new NetDiscovery(this);
            m_heartbeatCounter = new NetFrequencyCounter(3.0f);

            m_randomIdentifier = new byte[8];
            NetRandom.Instance.NextBytes(m_randomIdentifier);

            m_unsentOutOfBandMessages   = new NetQueue <NetBuffer>();
            m_unsentOutOfBandRecipients = new NetQueue <IPEndPoint>();
            m_susmQueue = new Queue <SUSystemMessage>();

            // default enabled message types
            m_enabledMessageTypes =
                NetMessageType.Data | NetMessageType.StatusChanged | NetMessageType.ServerDiscovered |
                NetMessageType.DebugMessage | NetMessageType.Receipt;
        }
Пример #5
0
        protected NetBase(NetConfiguration config)
        {
            Debug.Assert(config != null, "Config must not be null");
            if (string.IsNullOrEmpty(config.ApplicationIdentifier))
                throw new ArgumentException("Must set ApplicationIdentifier in NetConfiguration!");
            m_config = config;
            m_receiveBuffer = new NetBuffer(config.ReceiveBufferSize);
            m_sendBuffer = new NetBuffer(config.SendBufferSize);
            m_senderRemote = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
            m_statistics = new NetBaseStatistics();
            m_receivedMessages = new NetQueue<IncomingNetMessage>(4);
            m_scratchBuffer = new NetBuffer(32);
            m_bindLock = new object();
            m_discovery = new NetDiscovery(this);

            m_randomIdentifier = new byte[8];
            NetRandom.Instance.NextBytes(m_randomIdentifier);

            m_unsentOutOfBandMessages = new NetQueue<NetBuffer>();
            m_unsentOutOfBandRecipients = new NetQueue<IPEndPoint>();
            m_susmQueue = new Queue<SUSystemMessage>();

            // default enabled message types
            m_enabledMessageTypes =
                NetMessageType.Data | NetMessageType.StatusChanged | NetMessageType.ServerDiscovered |
                NetMessageType.DebugMessage | NetMessageType.Receipt;
        }
Пример #6
0
        public static LidgrenNetworkSession GetServerNetworkSession()
        {
            NetConfiguration config = new NetConfiguration("NetServer");
            config.MaxConnections = 8;
            config.Port = 12345;

            return new LidgrenNetworkSession(new NetServerWrapper(new NetServer(config)));
        }
Пример #7
0
        public TankAClient()
        {
            NetConfiguration netConfig = new NetConfiguration("TankA");
            client = new NetClient(netConfig);
            readBuffer = client.CreateBuffer();

            timeBetweenFireReq = Tank.MinTBF - 50;

            clientIndex = 1;
        }
Пример #8
0
        public NetworkServer()
        {
            var cfg = new NetConfiguration("aav.defense");
            cfg.Address = IPAddress.Any;
            cfg.Port = 52244;
            cfg.AnswerDiscoveryRequests = true;
            _srv = new NetServer(cfg);

            _srv.Start();
        }
Пример #9
0
		public ImageClient()
		{
			InitializeComponent();

			NetConfiguration config = new NetConfiguration("imageservice");
			m_client = new NetClient(config);
			m_client.SimulatedMinimumLatency = 0.05f;

			m_readBuffer = m_client.CreateBuffer();

			m_client.DiscoverLocalServers(14242);

			this.FormClosed += new FormClosedEventHandler(OnClosed);
			this.Show();
		}
Пример #10
0
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			s_mainForm = new Form1();

			NetConfiguration config = new NetConfiguration("OoBSample");
			s_client = new NetClient(config);
			s_client.SetMessageTypeEnabled(NetMessageType.OutOfBandData, true);
			s_client.Start();

			s_readBuffer = s_client.CreateBuffer();

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

			s_client.Shutdown("Bye");
		}
Пример #11
0
        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");
        }
        protected NetBase(NetConfiguration config)
        {
            Debug.Assert(config != null, "Config must not be null");
            if (string.IsNullOrEmpty(config.ApplicationIdentifier))
            {
                throw new ArgumentException("Must set ApplicationIdentifier in NetConfiguration!");
            }
            m_config        = config;
            m_receiveBuffer = new NetBuffer(config.ReceiveBufferSize);
            m_sendBuffer    = new NetBuffer(config.SendBufferSize);
            //by WuNan @2016/09/28 14:26:34
                        #if (UNITY_IOS || UNITY_TVOS) && !UNITY_EDITOR
            if (uLink.NetworkUtility.IsSupportIPv6())
            {
                m_senderRemote = (EndPoint) new NetworkEndPoint(IPAddress.IPv6Any, 0);
            }
            else
            {
                m_senderRemote = (EndPoint) new NetworkEndPoint(IPAddress.Any, 0);
            }
                        #else
            m_senderRemote = (EndPoint) new NetworkEndPoint(IPAddress.Any, 0);
                        #endif
            m_statistics       = new NetBaseStatistics();
            m_receivedMessages = new NetQueue <IncomingNetMessage>(4);
            m_tempBuffer       = new NetBuffer(256);
            m_discovery        = new NetDiscovery(this);
            m_heartbeatCounter = new NetFrequencyCounter(3.0f);

            m_localRndSignature = new byte[NetConstants.SignatureByteSize];
            NetRandom.Instance.NextBytes(m_localRndSignature);

            m_unsentOutOfBandMessages   = new NetQueue <NetBuffer>();
            m_unsentOutOfBandRecipients = new NetQueue <NetworkEndPoint>();
            m_susmQueue = new Queue <SUSystemMessage>();

            // default enabled message types
            m_enabledMessageTypes =
                NetMessageType.Data | NetMessageType.StatusChanged;
        }
Пример #13
0
		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");
		}
Пример #14
0
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			s_mainForm = new Form1();

			NetConfiguration config = new NetConfiguration("largepacket");
			config.Port = 14242;
			config.MaxConnections = 16;
			s_server = new NetServer(config);
			s_server.SimulatedLoss = 0.03f; // 3 %
			s_server.SimulatedMinimumLatency = 0.1f; // 100 ms
			s_server.SimulatedLatencyVariance = 0.05f; // 100-150 ms actually

			//m_server.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
			s_server.Start();

			s_readBuffer = s_server.CreateBuffer();

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

			s_server.Shutdown("Application exiting");
		}
Пример #15
0
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			s_mainForm = new Form1();

			s_nextPixelToSend = new Dictionary<NetConnection, uint>();

			NetConfiguration config = new NetConfiguration("imageservice");
			config.Port = 14242;
			config.MaxConnections = 64;
			config.ThrottleBytesPerSecond = 25000;
			s_server = new NetServer(config);
			s_server.SimulatedMinimumLatency = 0.05f;
			s_server.SimulatedLoss = m_loss;
			s_fpsStart = NetTime.Now;

			s_readBuffer = s_server.CreateBuffer();

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

			s_server.Shutdown("Application exit");
		}
Пример #16
0
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			m_mainForm = new Form1();

			NetConfiguration config = new NetConfiguration("largepacket");
			config.SendBufferSize = 128000;
			config.ThrottleBytesPerSecond = 8192;
			m_client = new NetClient(config);
			m_client.SimulatedLoss = 0.03f; // 3 %
			m_client.SimulatedMinimumLatency = 0.1f; // 100 ms
			m_client.SimulatedLatencyVariance = 0.05f; // 100-150 ms actually

			//m_client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
			m_client.SetMessageTypeEnabled(NetMessageType.Receipt, true);

			m_readBuffer = m_client.CreateBuffer();

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

			m_client.Shutdown("Application exiting");
		}
Пример #17
0
        static void Main(string[] args)
        {
            NetConfiguration config = new NetConfiguration("durable");
            NetClient client = new NetClient(config);

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

            // wait half a second to allow server to start up in Visual Studio
            Thread.Sleep(500);

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

            // connect to localhost
            client.Connect("localhost", 14242, Encoding.ASCII.GetBytes("Hail from client"));

            // enable some library messages
            client.SetMessageTypeEnabled(NetMessageType.BadMessageReceived, true);
            //client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
            client.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);

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

            // create a stopwatch
            Stopwatch sw = new Stopwatch();
            sw.Start();
            int loops = 0;

            while (!Console.KeyAvailable)
            {
                NetMessageType type;
                if (client.ReadMessage(buffer, out type))
                {
                    switch (type)
                    {
                        case NetMessageType.StatusChanged:
                            if (client.ServerConnection.RemoteHailData != null)
                                Output(wrt, "New status: " + client.Status + " (" + buffer.ReadString() + ") Remote hail is: " + Encoding.ASCII.GetString(client.ServerConnection.RemoteHailData));
                            else
                                Output(wrt, "New status: " + client.Status + " (" + buffer.ReadString() + ") Remote hail hasn't arrived.");
                            break;
                        case NetMessageType.BadMessageReceived:
                        case NetMessageType.ConnectionRejected:
                        case NetMessageType.DebugMessage:
                        case NetMessageType.VerboseDebugMessage:
                            //
                            // These types of messages all contain a string in the buffer; display it.
                            //
                            Output(wrt, buffer.ReadString());
                            break;
                        case NetMessageType.Data:
                        default:
                            //
                            // For this application; server doesn't send any data... so Data messages are unhandled
                            //
                            Output(wrt, "Unhandled: " + type + " " + buffer.ToString());
                            break;
                    }
                }

                // send a message every second
                if (client.Status == NetConnectionStatus.Connected && sw.Elapsed.TotalMilliseconds >= 516)
                {
                    loops++;
                    //Console.WriteLine("Sending message #" + loops);
                    Console.Title = "Client; Messages sent: " + loops;

                    Output(wrt, "Sending #" + loops + " at " + NetTime.ToMillis(NetTime.Now));
                    NetBuffer send = client.CreateBuffer();
                    send.Write("Message #" + loops);
                    client.SendMessage(send, NetChannel.ReliableInOrder14);

                    sw.Reset();
                    sw.Start();
                }

                Thread.Sleep(1);
            }

            // clean shutdown
            client.Shutdown("Application exiting");
            wrt.Close();
        }
Пример #18
0
 /// <summary>
 /// Creates a new NetServer
 /// </summary>
 public NetServer(NetConfiguration config)
     : base(config)
 {
     m_connections = new List<NetConnection>();
     m_connectionLookup = new Dictionary<IPEndPoint, NetConnection>();
 }
Пример #19
0
        public bool Start()
        {
            //Setup the variable toggles
            varBindingsInitialize();

            int tmpMaxPlayers = 16;

            // Read in from the config file.
            DatafileWriter dataFile = new DatafileWriter("server.config.txt");
            if (dataFile.Data.ContainsKey("winningcash"))
                winningCashAmount = uint.Parse(dataFile.Data["winningcash"], System.Globalization.CultureInfo.InvariantCulture);
            if (dataFile.Data.ContainsKey("includelava"))
                includeLava = bool.Parse(dataFile.Data["includelava"]);
            if (dataFile.Data.ContainsKey("orefactor"))
                oreFactor = uint.Parse(dataFile.Data["orefactor"], System.Globalization.CultureInfo.InvariantCulture);
            if (dataFile.Data.ContainsKey("maxplayers"))
                tmpMaxPlayers = (int)Math.Min(32, uint.Parse(dataFile.Data["maxplayers"], System.Globalization.CultureInfo.InvariantCulture));
            if (dataFile.Data.ContainsKey("public"))
                varSet("public", bool.Parse(dataFile.Data["public"]), true);
            if (dataFile.Data.ContainsKey("servername"))
                varSet("name", dataFile.Data["servername"], true);
            if (dataFile.Data.ContainsKey("sandbox"))
                varSet("sandbox", bool.Parse(dataFile.Data["sandbox"]), true);
            if (dataFile.Data.ContainsKey("notnt"))
                varSet("tnt", !bool.Parse(dataFile.Data["notnt"]), true);
            if (dataFile.Data.ContainsKey("sphericaltnt"))
                varSet("stnt", bool.Parse(dataFile.Data["sphericaltnt"]), true);
            if (dataFile.Data.ContainsKey("insanelava"))
                varSet("insanelava", bool.Parse(dataFile.Data["insanelava"]), true);
            if (dataFile.Data.ContainsKey("shockspreadslava"))
                varSet("sspreads", bool.Parse(dataFile.Data["shockspreadslava"]), true);
            if (dataFile.Data.ContainsKey("roadabsorbs"))
                varSet("roadabsorbs", bool.Parse(dataFile.Data["roadabsorbs"]), true);
            if (dataFile.Data.ContainsKey("minelava"))
                varSet("minelava", bool.Parse(dataFile.Data["minelava"]), true);
            if (dataFile.Data.ContainsKey("levelname"))
                levelToLoad = dataFile.Data["levelname"];
            if (dataFile.Data.ContainsKey("greeter"))
                varSet("greeter", dataFile.Data["greeter"], true);

            bool autoannounce = true;
            if (dataFile.Data.ContainsKey("autoannounce"))
                autoannounce = bool.Parse(dataFile.Data["autoannounce"]);

            // Load the ban-list.
            banList = LoadBanList();

            // Load the admin-list
            admins = LoadAdminList();

            if (tmpMaxPlayers >= 0)
                varSet("maxplayers", tmpMaxPlayers, true);

            // Initialize the server.
            NetConfiguration netConfig = new NetConfiguration("InfiniminerPlus");
            netConfig.MaxConnections = (int)varGetI("maxplayers");
            netConfig.Port = 5565;
            netServer = new InfiniminerNetServer(netConfig);
            netServer.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true);
            //netServer.SimulatedMinimumLatency = 0.1f;
            //netServer.SimulatedLatencyVariance = 0.05f;
            //netServer.SimulatedLoss = 0.1f;
            //netServer.SimulatedDuplicates = 0.05f;
            netServer.Start();

            // Initialize variables we'll use.
            NetBuffer msgBuffer = netServer.CreateBuffer();
            NetMessageType msgType;
            NetConnection msgSender;

            // Store the last time that we did a flow calculation.
            DateTime lastFlowCalc = DateTime.Now;

            //Check if we should autoload a level
            if (dataFile.Data.ContainsKey("autoload") && bool.Parse(dataFile.Data["autoload"]))
            {
                blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE];
                blockCreatorTeam = new PlayerTeam[MAPSIZE, MAPSIZE, MAPSIZE];
                LoadLevel(levelToLoad);
            }
            else
            {
                // Calculate initial lava flows.
                ConsoleWrite("CALCULATING INITIAL LAVA FLOWS");
                ConsoleWrite("TOTAL LAVA BLOCKS = " + newMap());
            }

            //Caculate the shape of spherical tnt explosions
            CalculateExplosionPattern();

            // Send the initial server list update.
            if (autoannounce)
                PublicServerListUpdate(true);

            lastMapBackup = DateTime.Now;

            // Main server loop!
            ConsoleWrite("SERVER READY");
            while (keepRunning)
            {
                // Process any messages that are here.
                while (netServer.ReadMessage(msgBuffer, out msgType, out msgSender))
                {
                    try
                    {
                        switch (msgType)
                        {
                            case NetMessageType.ConnectionApproval:
                                {
                                    Player newPlayer = new Player(msgSender, null);
                                    newPlayer.Handle = Defines.Sanitize(msgBuffer.ReadString()).Trim();
                                    if (newPlayer.Handle.Length == 0)
                                    {
                                        newPlayer.Handle = "Player";
                                    }

                                    string clientVersion = msgBuffer.ReadString();
                                    if (clientVersion != Defines.INFINIMINER_VERSION)
                                    {
                                        msgSender.Disapprove("VER;" + Defines.INFINIMINER_VERSION);
                                    }
                                    else if (banList.Contains(newPlayer.IP))
                                    {
                                        msgSender.Disapprove("BAN;");
                                    }/*
                                else if (playerList.Count == maxPlayers)
                                {
                                    msgSender.Disapprove("FULL;");
                                }*/
                                    else
                                    {
                                        if (admins.ContainsKey(newPlayer.IP))
                                            newPlayer.admin = admins[newPlayer.IP];
                                        playerList[msgSender] = newPlayer;
                                        //Check if we should compress the map for the client
                                        try
                                        {
                                            bool compression = msgBuffer.ReadBoolean();
                                            if (compression)
                                                playerList[msgSender].compression = true;
                                        }
                                        catch { }
                                        toGreet.Add(msgSender);
                                        this.netServer.SanityCheck(msgSender);
                                        msgSender.Approve();
                                        PublicServerListUpdate(true);
                                    }
                                }
                                break;

                            case NetMessageType.StatusChanged:
                                {
                                    if (!this.playerList.ContainsKey(msgSender))
                                    {
                                        break;
                                    }

                                    Player player = playerList[msgSender];

                                    if (msgSender.Status == NetConnectionStatus.Connected)
                                    {
                                        ConsoleWrite("CONNECT: " + playerList[msgSender].Handle + " ( " + playerList[msgSender].IP + " )");
                                        SendCurrentMap(msgSender);
                                        SendPlayerJoined(player);
                                        PublicServerListUpdate();
                                    }

                                    else if (msgSender.Status == NetConnectionStatus.Disconnected)
                                    {
                                        ConsoleWrite("DISCONNECT: " + playerList[msgSender].Handle);
                                        SendPlayerLeft(player, player.Kicked ? "WAS KICKED FROM THE GAME!" : "HAS ABANDONED THEIR DUTIES!");
                                        if (playerList.ContainsKey(msgSender))
                                            playerList.Remove(msgSender);
                                        PublicServerListUpdate();
                                    }
                                }
                                break;

                            case NetMessageType.Data:
                                {
                                    if (!this.playerList.ContainsKey(msgSender))
                                    {
                                        break;
                                    }

                                    Player player = playerList[msgSender];

                                    //If player isnt arround we dont care anymore - Cbock
                                    //If player is suspected of modding ignore updates for this cycle - Cbock
                                    if (player.Kicked == true || player.Flagged == true)
                                        break;

                                    InfiniminerMessage dataType = (InfiniminerMessage)msgBuffer.ReadByte();
                                    switch (dataType)
                                    {
                                        case InfiniminerMessage.ChatMessage:
                                            {
                                                // Read the data from the packet.
                                                ChatMessageType chatType = (ChatMessageType)msgBuffer.ReadByte();
                                                string chatString = Defines.Sanitize(msgBuffer.ReadString());
                                                if (!ProcessCommand(chatString, GetAdmin(playerList[msgSender].IP), playerList[msgSender]))
                                                {
                                                    ConsoleWrite("CHAT: (" + player.Handle + ") " + chatString);

                                                    // Append identifier information.
                                                    if (chatType == ChatMessageType.SayAll)
                                                        chatString = player.Handle + " (ALL): " + chatString;
                                                    else
                                                        chatString = player.Handle + " (TEAM): " + chatString;

                                                    // Construct the message packet.
                                                    NetBuffer chatPacket = netServer.CreateBuffer();
                                                    chatPacket.Write((byte)InfiniminerMessage.ChatMessage);
                                                    chatPacket.Write((byte)((player.Team == PlayerTeam.Red) ? ChatMessageType.SayRedTeam : ChatMessageType.SayBlueTeam));
                                                    chatPacket.Write(chatString);

                                                    // Send the packet to people who should recieve it.
                                                    foreach (Player p in playerList.Values)
                                                    {
                                                        if (chatType == ChatMessageType.SayAll ||
                                                            chatType == ChatMessageType.SayBlueTeam && p.Team == PlayerTeam.Blue ||
                                                            chatType == ChatMessageType.SayRedTeam && p.Team == PlayerTeam.Red)
                                                            if (p.NetConn.Status == NetConnectionStatus.Connected)
                                                                netServer.SendMessage(chatPacket, p.NetConn, NetChannel.ReliableInOrder3);
                                                    }
                                                }
                                            }
                                            break;

                                        case InfiniminerMessage.UseTool:
                                            {
                                                Vector3 playerPosition = msgBuffer.ReadVector3();
                                                Vector3 playerHeading = msgBuffer.ReadVector3();
                                                PlayerTools playerTool = (PlayerTools)msgBuffer.ReadByte();
                                                BlockType blockType = (BlockType)msgBuffer.ReadByte();
                                                switch (playerTool)
                                                {

                                                    case PlayerTools.Pickaxe:
                                                        //Modification to prevent client from ignoring axe cooldown times - Cbock
                                                        updateTime = DateTime.Now - player.AxeUsed;
                                                        if (updateTime.TotalSeconds < 0.1f)
                                                        {
                                                            player.Flagged = true;
                                                        }
                                                        else
                                                        {
                                                            player.AxeUsed = DateTime.Now;
                                                            UsePickaxe(player, playerPosition, playerHeading);
                                                        }
                                                        break;
                                                    case PlayerTools.ConstructionGun:
                                                        //Modification to prevent client from ignoring gun cooldown times - Cbock
                                                        updateTime = DateTime.Now - player.GunUsed;
                                                        if (updateTime.TotalSeconds < 0.35f)
                                                        {
                                                            player.Flagged = true;
                                                        }
                                                        else
                                                        {
                                                            player.GunUsed = DateTime.Now;
                                                            UseConstructionGun(player, playerPosition, playerHeading, blockType);
                                                        }
                                                        //End Mod
                                                        break;
                                                    case PlayerTools.DeconstructionGun:
                                                        //Modification to prevent client from ignoring gun cooldown times - Cbock
                                                        updateTime = DateTime.Now - player.GunUsed;
                                                        if (updateTime.TotalSeconds < 0.35f)
                                                        {
                                                            player.Flagged = true;
                                                        }
                                                        else
                                                        {
                                                            player.GunUsed = DateTime.Now;
                                                            UseDeconstructionGun(player, playerPosition, playerHeading);
                                                        }
                                                        //End Mod
                                                        break;
                                                    case PlayerTools.ProspectingRadar:
                                                        UseSignPainter(player, playerPosition, playerHeading);
                                                        break;
                                                    case PlayerTools.Detonator:
                                                        UseDetonator(player);
                                                        break;
                                                }
                                            }
                                            break;

                                        case InfiniminerMessage.SelectClass:
                                            {
                                                PlayerClass playerClass = (PlayerClass)msgBuffer.ReadByte();
                                                ConsoleWrite("SELECT_CLASS: " + player.Handle + ", " + playerClass.ToString());
                                                switch (playerClass)
                                                {
                                                    case PlayerClass.Engineer:
                                                        player.OreMax = 350;
                                                        player.WeightMax = 4;
                                                        break;
                                                    case PlayerClass.Miner:
                                                        player.OreMax = 200;
                                                        player.WeightMax = 8;
                                                        break;
                                                    case PlayerClass.Prospector:
                                                        player.OreMax = 200;
                                                        player.WeightMax = 4;
                                                        break;
                                                    case PlayerClass.Sapper:
                                                        player.OreMax = 200;
                                                        player.WeightMax = 4;
                                                        break;
                                                }
                                                SendResourceUpdate(player);
                                            }
                                            break;

                                        case InfiniminerMessage.PlayerSetTeam:
                                            {
                                                PlayerTeam playerTeam = (PlayerTeam)msgBuffer.ReadByte();
                                                ConsoleWrite("SELECT_TEAM: " + player.Handle + ", " + playerTeam.ToString());
                                                player.Team = playerTeam;
                                                SendResourceUpdate(player);
                                                SendPlayerSetTeam(player);
                                            }
                                            break;

                                        case InfiniminerMessage.PlayerDead:
                                            {
                                                ConsoleWrite("PLAYER_DEAD: " + player.Handle);
                                                player.Ore = 0;
                                                player.Cash = 0;
                                                player.Weight = 0;
                                                player.Alive = false;
                                                SendResourceUpdate(player);
                                                SendPlayerDead(player);

                                                string deathMessage = msgBuffer.ReadString();
                                                if (deathMessage != "")
                                                {
                                                    msgBuffer = netServer.CreateBuffer();
                                                    msgBuffer.Write((byte)InfiniminerMessage.ChatMessage);
                                                    msgBuffer.Write((byte)(player.Team == PlayerTeam.Red ? ChatMessageType.SayRedTeam : ChatMessageType.SayBlueTeam));
                                                    msgBuffer.Write(player.Handle + " " + deathMessage);
                                                    foreach (NetConnection netConn in playerList.Keys)
                                                        if (netConn.Status == NetConnectionStatus.Connected)
                                                            netServer.SendMessage(msgBuffer, netConn, NetChannel.ReliableInOrder3);
                                                }
                                            }
                                            break;

                                        case InfiniminerMessage.PlayerAlive:
                                            {
                                                if (toGreet.Contains(msgSender))
                                                {
                                                    string greeting = varGetS("greeter");
                                                    greeting = greeting.Replace("[name]", playerList[msgSender].Handle);
                                                    if (greeting != "")
                                                    {
                                                        NetBuffer greetBuffer = netServer.CreateBuffer();
                                                        greetBuffer.Write((byte)InfiniminerMessage.ChatMessage);
                                                        greetBuffer.Write((byte)ChatMessageType.SayAll);
                                                        greetBuffer.Write(Defines.Sanitize(greeting));
                                                        netServer.SendMessage(greetBuffer, msgSender, NetChannel.ReliableInOrder3);
                                                    }
                                                    toGreet.Remove(msgSender);
                                                }
                                                ConsoleWrite("PLAYER_ALIVE: " + player.Handle);
                                                player.Ore = 0;
                                                player.Cash = 0;
                                                player.Weight = 0;
                                                player.Alive = true;
                                                SendResourceUpdate(player);
                                                SendPlayerAlive(player);
                                            }
                                            break;

                                        case InfiniminerMessage.PlayerUpdate:
                                            {
                                                player.Position = msgBuffer.ReadVector3();
                                                player.Heading = msgBuffer.ReadVector3();

                                                // Code to pervent speed, no clipping, and flying mods - DCaudill

                                                // Find out if the player is in the air
                                                Vector3 footPosition = player.Position + new Vector3(0f, -1.5f, 0f);
                                                BlockType standingOnBlock = BlockAtPoint(new Vector3(footPosition.X, footPosition.Y, footPosition.Z));
                                                bool inAir = false;
                                                if (standingOnBlock == BlockType.None && !CheckOnLadder(player))
                                                    inAir = true;

                                                // Update the players list of last 10 updates
                                                playerList[msgSender].UpdatePositionServer(player.Position, inAir, player.Alive, DateTime.Now);

                                                // Check for speed mods and kick if found
                                                if (CheckSpeed(player) && player.positionList.Count > 9)
                                                {
                                                    KickPlayer(player.IP);
                                                    SendServerMessage(player.Handle + " was kicked for speed mods, Sorry");
                                                    ConsoleWrite(player.Handle + " was kicked for speed mods, Sorry");
                                                }

                                                // Check for flying mods and kick if found
                                                if (CheckFlying(player) && player.positionList.Count > 9)
                                                {
                                                    KickPlayer(player.IP);
                                                    SendServerMessage(player.Handle + " was kicked for flying, Sorry");
                                                    ConsoleWrite(player.Handle + " was kicked for flying mods, Sorry");
                                                }

                                                // Check for no clipping mods and kick if found
                                                if (CheckNoClipping(player) && player.positionList.Count > 9)
                                                {
                                                    KickPlayer(player.IP);
                                                    SendServerMessage(player.Handle + " was kicked for no clipping, Sorry");
                                                    ConsoleWrite(player.Handle + " was kicked for no clipping, Sorry");
                                                }

                                                player.Tool = (PlayerTools)msgBuffer.ReadByte();
                                                player.UsingTool = msgBuffer.ReadBoolean();
                                                SendPlayerUpdate(player);

                                            }
                                            break;

                                        case InfiniminerMessage.DepositOre:
                                            {
                                                DepositOre(player);
                                                foreach (Player p in playerList.Values)
                                                    SendResourceUpdate(p);
                                            }
                                            break;

                                        case InfiniminerMessage.WithdrawOre:
                                            {
                                                WithdrawOre(player);
                                                foreach (Player p in playerList.Values)
                                                    SendResourceUpdate(p);
                                            }
                                            break;

                                        case InfiniminerMessage.PlayerPing:
                                            {
                                                SendPlayerPing((uint)msgBuffer.ReadInt32());
                                            }
                                            break;

                                        case InfiniminerMessage.PlaySound:
                                            {
                                                InfiniminerSound sound = (InfiniminerSound)msgBuffer.ReadByte();
                                                Vector3 position = msgBuffer.ReadVector3();
                                                PlaySound(sound, position);
                                            }
                                            break;
                                    }
                                }
                                break;
                        }
                    }
                    catch { }
                }

                // Unflag all clients after data is finished being parsed - Cbock
                foreach (Player p in playerList.Values)
                {
                    p.Flagged = false;
                }

                //Time to backup map?
                TimeSpan mapUpdateTimeSpan = DateTime.Now - lastMapBackup;
                if (mapUpdateTimeSpan.TotalMinutes > 5)
                {
                    SaveLevel("autoBK.lvl");
                }

                // Time to send a new server update?
                PublicServerListUpdate(); //It checks for public server / time span

                //Time to terminate finished map sending threads?
                TerminateFinishedThreads();

                // Check for players who are in the zone to deposit.
                DepositForPlayers();

                // Is it time to do a lava calculation? If so, do it!
                TimeSpan timeSpan = DateTime.Now - lastFlowCalc;
                if (timeSpan.TotalMilliseconds > 500)
                {
                    DoLavaStuff();
                    lastFlowCalc = DateTime.Now;
                }

                // Handle console keypresses.
                while (Console.KeyAvailable)
                {
                    ConsoleKeyInfo keyInfo = Console.ReadKey();
                    if (keyInfo.Key == ConsoleKey.Enter)
                        ConsoleProcessInput();
                    else if (keyInfo.Key == ConsoleKey.Backspace)
                    {
                        if (consoleInput.Length > 0)
                            consoleInput = consoleInput.Substring(0, consoleInput.Length - 1);
                        ConsoleRedraw();
                    }
                    else
                    {
                        consoleInput += keyInfo.KeyChar;
                        ConsoleRedraw();
                    }
                }

                // Is the game over?
                if (winningTeam != PlayerTeam.None && !restartTriggered)
                {
                    BroadcastGameOver();
                    restartTriggered = true;
                    restartTime = DateTime.Now.AddSeconds(10);
                }

                // Restart the server?
                if (restartTriggered && DateTime.Now > restartTime)
                {
                    SaveLevel("autosave_" + (UInt64)DateTime.Now.ToBinary() + ".lvl");
                    netServer.Shutdown("The server is restarting.");
                    return true;
                }

                // Pass control over to waiting threads.
                Thread.Sleep(1);
            }

            MessageAll("Server going down NOW!");

            netServer.Shutdown("The server was terminated.");
            return false;
        }
 /// <summary>
 /// Creates a new NetClient
 /// </summary>
 public NetClient(NetConfiguration config)
     : base(config)
 {
 }
Пример #21
0
        public bool Start()
        {
            //Setup the variable toggles
            varBindingsInitialize();
            int tmpMaxPlayers = 16;

            // Read in from the config file.
            DatafileWriter dataFile = new DatafileWriter("server.config.txt");
            if (dataFile.Data.ContainsKey("winningcash"))
                winningCashAmount = uint.Parse(dataFile.Data["winningcash"], System.Globalization.CultureInfo.InvariantCulture);
            if (dataFile.Data.ContainsKey("includelava"))
                includeLava = bool.Parse(dataFile.Data["includelava"]);
            if (dataFile.Data.ContainsKey("includewater"))
                includeLava = bool.Parse(dataFile.Data["includewater"]);
            if (dataFile.Data.ContainsKey("orefactor"))
                oreFactor = uint.Parse(dataFile.Data["orefactor"], System.Globalization.CultureInfo.InvariantCulture);
            if (dataFile.Data.ContainsKey("maxplayers"))
                tmpMaxPlayers = (int)Math.Min(32, uint.Parse(dataFile.Data["maxplayers"], System.Globalization.CultureInfo.InvariantCulture));
            if (dataFile.Data.ContainsKey("public"))
                varSet("public", bool.Parse(dataFile.Data["public"]), true);
            if (dataFile.Data.ContainsKey("servername"))
                varSet("name", dataFile.Data["servername"], true);
            if (dataFile.Data.ContainsKey("sandbox"))
                varSet("sandbox", bool.Parse(dataFile.Data["sandbox"]), true);
            if (dataFile.Data.ContainsKey("notnt"))
                varSet("tnt", !bool.Parse(dataFile.Data["notnt"]), true);
            if (dataFile.Data.ContainsKey("sphericaltnt"))
                varSet("stnt", bool.Parse(dataFile.Data["sphericaltnt"]), true);
            if (dataFile.Data.ContainsKey("insane"))
                varSet("insane", bool.Parse(dataFile.Data["insane"]), true);
            if (dataFile.Data.ContainsKey("roadabsorbs"))
                varSet("roadabsorbs", bool.Parse(dataFile.Data["roadabsorbs"]), true);
            if (dataFile.Data.ContainsKey("minelava"))
                varSet("minelava", bool.Parse(dataFile.Data["minelava"]), true);
            if (dataFile.Data.ContainsKey("levelname"))
                levelToLoad = dataFile.Data["levelname"];
            if (dataFile.Data.ContainsKey("greeter"))
                varSet("greeter", dataFile.Data["greeter"],true);

            bool autoannounce = true;
            if (dataFile.Data.ContainsKey("autoannounce"))
                autoannounce = bool.Parse(dataFile.Data["autoannounce"]);

            // Load the ban-list.
            banList = LoadBanList();

            // Load the admin-list
            admins = LoadAdminList();

            if (tmpMaxPlayers>=0)
                varSet("maxplayers", tmpMaxPlayers, true);

            // Initialize the server.
            NetConfiguration netConfig = new NetConfiguration("InfiniminerPlus");
            netConfig.MaxConnections = (int)varGetI("maxplayers");
            netConfig.Port = 5565;
            netServer = new InfiniminerNetServer(netConfig);
            netServer.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true);

            //netServer.SimulatedMinimumLatency = 0.5f;
               // netServer.SimulatedLatencyVariance = 0.05f;
               // netServer.SimulatedLoss = 0.2f;
               // netServer.SimulatedDuplicates = 0.05f;
            //netServer.Configuration.SendBufferSize = 2048000;
            //netServer.Start();//starts too early
            // Initialize variables we'll use.
            NetBuffer msgBuffer = netServer.CreateBuffer();
            NetMessageType msgType;
            NetConnection msgSender;

            // Store the last time that we did a flow calculation.
            DateTime lastFlowCalc = DateTime.Now;
            DateTime lastFlowCalcZ = DateTime.Now;//temporary
            DateTime sysTimer = DateTime.Now;
            //Check if we should autoload a level
            if (dataFile.Data.ContainsKey("autoload") && bool.Parse(dataFile.Data["autoload"]))
            {
                blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE];
                blockCreatorTeam = new PlayerTeam[MAPSIZE, MAPSIZE, MAPSIZE];
                LoadLevel(levelToLoad);

                lavaBlockCount = 0;
                waterBlockCount = 0;
                int burstBlockCount = 0;

                for (ushort i = 0; i < MAPSIZE; i++)
                    for (ushort j = 0; j < MAPSIZE; j++)
                        for (ushort k = 0; k < MAPSIZE; k++)
                        {
                            if (blockList[i, j, k] == BlockType.Lava)
                            {
                                lavaBlockCount += 1;
                            }
                            else if (blockList[i, j, k] == BlockType.Water)
                            {
                                waterBlockCount += 1;
                            }
                            else if (blockList[i, j, k] == BlockType.MagmaBurst)
                            {
                                burstBlockCount += 1;
                            }
                        }

                ConsoleWrite(waterBlockCount + " water blocks, " + lavaBlockCount + " lava blocks, " + burstBlockCount + " possible bursts." );
            }
            else
            {
                // Calculate initial lava flows.
                ConsoleWrite("CALCULATING INITIAL LIQUID BLOCKS");
                newMap();

                lavaBlockCount = 0;
                waterBlockCount = 0;
                int burstBlockCount = 0;
                for (ushort i = 0; i < MAPSIZE; i++)
                    for (ushort j = 0; j < MAPSIZE; j++)
                        for (ushort k = 0; k < MAPSIZE; k++)
                        {
                            if (blockList[i, j, k] == BlockType.Lava)
                            {
                                lavaBlockCount += 1;
                            }
                            else if (blockList[i, j, k] == BlockType.Water)
                            {
                                waterBlockCount += 1;
                            }
                            else if (blockList[i, j, k] == BlockType.MagmaBurst)
                            {
                                burstBlockCount += 1;
                            }
                        }

                ConsoleWrite(waterBlockCount + " water blocks, " + lavaBlockCount + " lava blocks, " + burstBlockCount + " possible bursts.");
            }

            //Caculate the shape of spherical tnt explosions
            CalculateExplosionPattern();

            // Send the initial server list update.
            if (autoannounce)
                PublicServerListUpdate(true);

            lastMapBackup = DateTime.Now;

            DateTime lastFPScheck = DateTime.Now;
            double frameRate = 0;

            // Main server loop!
            netServer.Start();
            ConsoleWrite("SERVER READY");

            if (!physics.IsAlive)
            {
                ConsoleWrite("Physics thread is limp.");
            }

            while (keepRunning)
            {
                if (!physics.IsAlive)
                {
                    ConsoleWrite("Physics thread died.");
                   // physics.Abort();
                   // physics.Join();
                    //physics.Start();
                }

                frameCount = frameCount + 1;
                if (lastFPScheck <= DateTime.Now - TimeSpan.FromMilliseconds(1000))
                {
                    lastFPScheck = DateTime.Now;
                    frameRate = frameCount;// / gameTime.ElapsedTotalTime.TotalSeconds;

                    if (sleeping == false && frameCount < 20)
                    {
                        ConsoleWrite("Heavy load: " + frameCount + " FPS");
                    }
                    frameCount = 0;
                }

                // Process any messages that are here.
                while (netServer.ReadMessage(msgBuffer, out msgType, out msgSender))
                {
                    try
                    {
                        switch (msgType)
                        {
                            case NetMessageType.ConnectionApproval:
                                {
                                    Player newPlayer = new Player(msgSender, null);
                                    newPlayer.Handle = Defines.Sanitize(msgBuffer.ReadString()).Trim();
                                    if (newPlayer.Handle.Length == 0)
                                    {
                                        newPlayer.Handle = "Player";
                                    }

                                    string clientVersion = msgBuffer.ReadString();
                                    if (clientVersion != Defines.INFINIMINER_VERSION)
                                    {
                                        msgSender.Disapprove("VER;" + Defines.INFINIMINER_VERSION);
                                    }
                                    else if (banList.Contains(newPlayer.IP))
                                    {
                                        msgSender.Disapprove("BAN;");
                                    }/*
                                else if (playerList.Count == maxPlayers)
                                {
                                    msgSender.Disapprove("FULL;");
                                }*/
                                    else
                                    {
                                        if (admins.ContainsKey(newPlayer.IP))
                                            newPlayer.admin = admins[newPlayer.IP];
                                        playerList[msgSender] = newPlayer;
                                        //Check if we should compress the map for the client
                                        try
                                        {
                                            bool compression = msgBuffer.ReadBoolean();
                                            if (compression)
                                                playerList[msgSender].compression = true;
                                        } catch { }
                                        toGreet.Add(msgSender);
                                        this.netServer.SanityCheck(msgSender);
                                        msgSender.Approve();
                                        PublicServerListUpdate(true);
                                    }
                                }
                                break;

                            case NetMessageType.StatusChanged:
                                {
                                    if (!this.playerList.ContainsKey(msgSender))
                                    {
                                        break;
                                    }

                                    Player player = playerList[msgSender];

                                    if (msgSender.Status == NetConnectionStatus.Connected)
                                    {
                                        if (sleeping == true)
                                        {
                                            sleeping = false;
                                            physicsEnabled = true;
                                        }
                                        ConsoleWrite("CONNECT: " + playerList[msgSender].Handle + " ( " + playerList[msgSender].IP + " )");
                                        SendCurrentMap(msgSender);
                                        SendPlayerJoined(player);
                                        PublicServerListUpdate();
                                    }

                                    else if (msgSender.Status == NetConnectionStatus.Disconnected)
                                    {
                                        ConsoleWrite("DISCONNECT: " + playerList[msgSender].Handle);
                                        SendPlayerLeft(player, player.Kicked ? "WAS KICKED FROM THE GAME!" : "HAS ABANDONED THEIR DUTIES!");
                                        if (playerList.ContainsKey(msgSender))
                                            playerList.Remove(msgSender);

                                        sleeping = true;
                                        foreach (Player p in playerList.Values)
                                        {
                                            sleeping = false;
                                        }

                                        if (sleeping == true)
                                        {
                                            ConsoleWrite("HIBERNATING");
                                            physicsEnabled = false;
                                        }

                                        PublicServerListUpdate();
                                    }
                                }
                                break;

                            case NetMessageType.Data:
                                {
                                    if (!this.playerList.ContainsKey(msgSender))
                                    {
                                        break;
                                    }

                                    Player player = playerList[msgSender];
                                    InfiniminerMessage dataType = (InfiniminerMessage)msgBuffer.ReadByte();
                                    switch (dataType)
                                    {
                                        case InfiniminerMessage.ChatMessage:
                                            {
                                                // Read the data from the packet.
                                                ChatMessageType chatType = (ChatMessageType)msgBuffer.ReadByte();
                                                string chatString = Defines.Sanitize(msgBuffer.ReadString());
                                                if (!ProcessCommand(chatString,GetAdmin(playerList[msgSender].IP),playerList[msgSender]))
                                                {
                                                    if (chatType == ChatMessageType.SayAll)
                                                    ConsoleWrite("CHAT: (" + player.Handle + ") " + chatString);

                                                    // Append identifier information.
                                                    if (chatType == ChatMessageType.SayAll)
                                                        chatString = player.Handle + " (ALL): " + chatString;
                                                    else
                                                        chatString = player.Handle + " (TEAM): " + chatString;

                                                    // Construct the message packet.
                                                    NetBuffer chatPacket = netServer.CreateBuffer();
                                                    chatPacket.Write((byte)InfiniminerMessage.ChatMessage);
                                                    chatPacket.Write((byte)((player.Team == PlayerTeam.Red) ? ChatMessageType.SayRedTeam : ChatMessageType.SayBlueTeam));
                                                    chatPacket.Write(chatString);

                                                    // Send the packet to people who should recieve it.
                                                    foreach (Player p in playerList.Values)
                                                    {
                                                        if (chatType == ChatMessageType.SayAll ||
                                                            chatType == ChatMessageType.SayBlueTeam && p.Team == PlayerTeam.Blue ||
                                                            chatType == ChatMessageType.SayRedTeam && p.Team == PlayerTeam.Red)
                                                            if (p.NetConn.Status == NetConnectionStatus.Connected)
                                                                netServer.SendMessage(chatPacket, p.NetConn, NetChannel.ReliableInOrder3);
                                                    }
                                                }
                                            }
                                            break;

                                        case InfiniminerMessage.UseTool:
                                            {
                                                Vector3 playerPosition = msgBuffer.ReadVector3();
                                                Vector3 playerHeading = msgBuffer.ReadVector3();
                                                PlayerTools playerTool = (PlayerTools)msgBuffer.ReadByte();
                                                BlockType blockType = (BlockType)msgBuffer.ReadByte();

                                                //getTo
                                                switch (playerTool)
                                                {
                                                    case PlayerTools.Pickaxe:
                                                        UsePickaxe(player, playerPosition, playerHeading);
                                                        break;
                                                    case PlayerTools.StrongArm:
                                                        if (player.Class == PlayerClass.Miner)
                                                        UseStrongArm(player, playerPosition, playerHeading);
                                                        break;
                                                    case PlayerTools.Smash:
                                                        //if(player.Class == PlayerClass.Sapper)
                                                        //UseSmash(player, playerPosition, playerHeading);
                                                        break;
                                                    case PlayerTools.ConstructionGun:
                                                        UseConstructionGun(player, playerPosition, playerHeading, blockType);
                                                        break;
                                                    case PlayerTools.DeconstructionGun:
                                                        UseDeconstructionGun(player, playerPosition, playerHeading);
                                                        break;
                                                    case PlayerTools.ProspectingRadar:
                                                        UseSignPainter(player, playerPosition, playerHeading);
                                                        break;
                                                    case PlayerTools.Detonator:
                                                        if (player.Class == PlayerClass.Sapper)
                                                        UseDetonator(player);
                                                        break;
                                                    case PlayerTools.Remote:
                                                        if (player.Class == PlayerClass.Engineer)
                                                        UseRemote(player);
                                                        break;
                                                    case PlayerTools.SetRemote:
                                                        if (player.Class == PlayerClass.Engineer)
                                                        SetRemote(player);
                                                        break;
                                                    case PlayerTools.ThrowBomb:
                                                        if (player.Class == PlayerClass.Sapper)
                                                        ThrowBomb(player, playerPosition, playerHeading);
                                                        break;
                                                    case PlayerTools.ThrowRope:
                                                        if (player.Class == PlayerClass.Prospector)
                                                            ThrowRope(player, playerPosition, playerHeading);
                                                        break;
                                                    case PlayerTools.Hide:
                                                        if (player.Class == PlayerClass.Prospector)
                                                            Hide(player);
                                                        break;
                                                }
                                            }
                                            break;

                                        case InfiniminerMessage.SelectClass:
                                            {
                                                PlayerClass playerClass = (PlayerClass)msgBuffer.ReadByte();
                                                player.Alive = false;
                                                ConsoleWrite("SELECT_CLASS: " + player.Handle + ", " + playerClass.ToString());
                                                switch (playerClass)
                                                {
                                                    case PlayerClass.Engineer:
                                                        player.Class = playerClass;
                                                        player.OreMax = 200 + (uint)(ResearchComplete[(byte)player.Team, 2] * 20);
                                                        player.WeightMax = 4 + (uint)(ResearchComplete[(byte)player.Team, 2]);
                                                        player.HealthMax = 100 + (uint)(ResearchComplete[(byte)player.Team,1]*20);
                                                        player.Health = player.HealthMax;
                                                        for (int a = 0; a < 100; a++)
                                                        {
                                                            player.Content[a] = 0;
                                                        }
                                                        break;
                                                    case PlayerClass.Miner://strong arm/throws blocks
                                                        player.Class = playerClass;
                                                        player.OreMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 2] * 20);
                                                        player.WeightMax = 10 + (uint)(ResearchComplete[(byte)player.Team, 2]);
                                                        player.HealthMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 1] * 20);
                                                        player.Health = player.HealthMax;
                                                        for (int a = 0; a < 100; a++)
                                                        {
                                                            player.Content[a] = 0;
                                                        }
                                                        break;
                                                    case PlayerClass.Prospector://profiteer/has prospectron/stealth/climb/traps
                                                        player.Class = playerClass;
                                                        player.OreMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 2] * 20);
                                                        player.WeightMax = 6 + (uint)(ResearchComplete[(byte)player.Team, 2]);
                                                        player.HealthMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 1] * 20);
                                                        player.Health = player.HealthMax;
                                                        for (int a = 0; a < 100; a++)
                                                        {
                                                            player.Content[a] = 0;
                                                        }
                                                        break;
                                                    case PlayerClass.Sapper://berserker/charge that knocks people and blocks away/repairs block
                                                        player.Class = playerClass;
                                                        player.OreMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 2] * 20);
                                                        player.WeightMax = 4 + (uint)(ResearchComplete[(byte)player.Team, 2]);
                                                        player.HealthMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 1] * 20);
                                                        player.Health = player.HealthMax;
                                                        for (int a = 0; a < 100; a++)
                                                        {
                                                            player.Content[a] = 0;
                                                        }
                                                        break;
                                                }
                                                SendResourceUpdate(player);
                                                SendContentUpdate(player);
                                                SendPlayerSetClass(player);
                                            }
                                            break;

                                        case InfiniminerMessage.PlayerSetTeam:
                                            {
                                                PlayerTeam playerTeam = (PlayerTeam)msgBuffer.ReadByte();
                                                ConsoleWrite("SELECT_TEAM: " + player.Handle + ", " + playerTeam.ToString());
                                                player.Team = playerTeam;
                                                player.Health = 0;
                                                player.Alive = false;
                                                Player_Dead(player, "");
                                                SendResourceUpdate(player);
                                                SendPlayerSetTeam(player);
                                            }
                                            break;

                                        case InfiniminerMessage.PlayerDead:
                                            {
                                                string deathMessage = msgBuffer.ReadString();
                                                if (player.Alive)
                                                {
                                                    Player_Dead(player, deathMessage);
                                                }
                                            }
                                            break;

                                        case InfiniminerMessage.PlayerAlive:
                                            {
                                                if (toGreet.Contains(msgSender))
                                                {
                                                    string greeting = varGetS("greeter");
                                                    greeting = greeting.Replace("[name]", playerList[msgSender].Handle);
                                                    if (greeting != "")
                                                    {
                                                        NetBuffer greetBuffer = netServer.CreateBuffer();
                                                        greetBuffer.Write((byte)InfiniminerMessage.ChatMessage);
                                                        greetBuffer.Write((byte)ChatMessageType.SayAll);
                                                        greetBuffer.Write(Defines.Sanitize(greeting));
                                                        netServer.SendMessage(greetBuffer, msgSender, NetChannel.ReliableInOrder3);
                                                    }
                                                    toGreet.Remove(msgSender);
                                                }
                                                ConsoleWrite("PLAYER_ALIVE: " + player.Handle);
                                                player.Ore = 0;
                                                player.Cash = 0;
                                                player.Weight = 0;
                                                player.Health = player.HealthMax;
                                                player.Alive = true;
                                                player.respawnTimer = DateTime.Now + TimeSpan.FromSeconds(5);
                                                SendResourceUpdate(player);
                                                SendPlayerAlive(player);
                                            }
                                            break;
                                        case InfiniminerMessage.PlayerRespawn:
                                            {
                                                SendPlayerRespawn(player);//new respawn
                                            }
                                            break;
                                        case InfiniminerMessage.PlayerUpdate:
                                            {
                                                if (player.Alive)
                                                {
                                                    player.Position = Auth_Position(msgBuffer.ReadVector3(), player, true);
                                                    player.Heading = Auth_Heading(msgBuffer.ReadVector3());
                                                    player.Tool = (PlayerTools)msgBuffer.ReadByte();
                                                    player.UsingTool = msgBuffer.ReadBoolean();
                                                    SendPlayerUpdate(player);
                                                }
                                            }
                                            break;
                                        case InfiniminerMessage.PlayerSlap:
                                            {
                                                if (player.Alive)
                                                {
                                                    if (player.playerToolCooldown > DateTime.Now)
                                                    {
                                                        break;//discard fast packet
                                                    }

                                                    player.Position = Auth_Position(msgBuffer.ReadVector3(), player, true);
                                                    player.Heading = Auth_Heading(msgBuffer.ReadVector3());
                                                    player.Tool = (PlayerTools)msgBuffer.ReadByte();
                                                    player.UsingTool = true;
                                                    Auth_Slap(player, msgBuffer.ReadUInt32());
                                                    SendPlayerUpdate(player);

                                                    player.playerToolCooldown = DateTime.Now + TimeSpan.FromSeconds((float)(player.GetToolCooldown(PlayerTools.Pickaxe)));

                                                    if (player.Class == PlayerClass.Prospector && player.Content[5] > 0)//reveal when hit
                                                    {
                                                        player.Content[6] = 0;//uncharge
                                                        player.Content[1] = 0;//reappear on radar
                                                        SendPlayerContentUpdate(player, 1);
                                                        player.Content[5] = 0;//sight
                                                        SendContentSpecificUpdate(player, 5);
                                                        SendContentSpecificUpdate(player, 6);
                                                        SendPlayerContentUpdate(player, 5);
                                                        SendServerMessageToPlayer("You have been revealed!", player.NetConn);
                                                        EffectAtPoint(player.Position - Vector3.UnitY * 1.5f, 1);
                                                    }
                                                }
                                            }
                                            break;
                                        case InfiniminerMessage.PlayerUpdate1://minus position
                                            {
                                                if (player.Alive)
                                                {
                                                    player.Heading = Auth_Heading(msgBuffer.ReadVector3());
                                                    player.Tool = (PlayerTools)msgBuffer.ReadByte();
                                                    player.UsingTool = msgBuffer.ReadBoolean();
                                                    SendPlayerUpdate(player);
                                                }
                                            }
                                            break;
                                        case InfiniminerMessage.PlayerUpdate2://minus position and heading
                                            {
                                                if (player.Alive)
                                                {
                                                    player.Tool = (PlayerTools)msgBuffer.ReadByte();
                                                    player.UsingTool = msgBuffer.ReadBoolean();
                                                    SendPlayerUpdate(player);
                                                }
                                            }
                                            break;
                                        case InfiniminerMessage.PlayerHurt://client speaks of fall damage
                                            {
                                                uint newhp = msgBuffer.ReadUInt32();
                                                if (newhp < player.Health)
                                                {
                                                    if (player.Team == PlayerTeam.Red)
                                                    {
                                                        DebrisEffectAtPoint((int)(player.Position.X), (int)(player.Position.Y), (int)(player.Position.Z), BlockType.SolidRed, 10 + (int)(player.Health - newhp));
                                                    }
                                                    else
                                                    {
                                                        DebrisEffectAtPoint((int)(player.Position.X), (int)(player.Position.Y), (int)(player.Position.Z), BlockType.SolidBlue, 10 + (int)(player.Health - newhp));
                                                    }

                                                    player.Health = newhp;
                                                    if (player.Health < 1)
                                                    {
                                                        Player_Dead(player, "FELL TO THEIR DEATH!");
                                                    }
                                                }
                                            }
                                            break;
                                        case InfiniminerMessage.PlayerPosition://server not interested in clients complaints about position
                                            {

                                            }
                                            break;
                                        case InfiniminerMessage.PlayerInteract://client speaks of mashing on block
                                            {
                                                player.Position = Auth_Position(msgBuffer.ReadVector3(), player, true);

                                                uint btn = msgBuffer.ReadUInt32();
                                                uint btnx = msgBuffer.ReadUInt32();
                                                uint btny = msgBuffer.ReadUInt32();
                                                uint btnz = msgBuffer.ReadUInt32();

                                                //if (blockList[btnx, btny, btnz] == BlockType.Pump || blockList[btnx, btny, btnz] == BlockType.Pipe || blockList[btnx, btny, btnz] == BlockType.Generator || blockList[btnx, btny, btnz] == BlockType.Barrel || blockList[btnx, btny, btnz] == BlockType.Switch)
                                                //{
                                                    if (Get3DDistance((int)btnx, (int)btny, (int)btnz, (int)player.Position.X, (int)player.Position.Y, (int)player.Position.Z) < 4)
                                                    {
                                                        PlayerInteract(player,btn, btnx, btny, btnz);
                                                    }
                                                //}
                                            }
                                            break;
                                        case InfiniminerMessage.DepositOre:
                                            {
                                                DepositOre(player);
                                                foreach (Player p in playerList.Values)
                                                    SendResourceUpdate(p);
                                            }
                                            break;

                                        case InfiniminerMessage.WithdrawOre:
                                            {
                                                WithdrawOre(player);
                                                foreach (Player p in playerList.Values)
                                                    SendResourceUpdate(p);
                                            }
                                            break;

                                        case InfiniminerMessage.PlayerPing:
                                            {
                                                if (player.Ping == 0)
                                                {
                                                    SendPlayerPing((uint)msgBuffer.ReadInt32());
                                                    player.Ping = 2;
                                                }
                                            }
                                            break;

                                        case InfiniminerMessage.PlaySound:
                                            {
                                                InfiniminerSound sound = (InfiniminerSound)msgBuffer.ReadByte();
                                                Vector3 position = msgBuffer.ReadVector3();
                                                PlaySoundForEveryoneElse(sound, position,player);
                                            }
                                            break;

                                        case InfiniminerMessage.DropItem:
                                            {
                                                DropItem(player, msgBuffer.ReadUInt32());
                                            }
                                            break;

                                        case InfiniminerMessage.GetItem:
                                            {
                                                //verify players position before get
                                                player.Position = Auth_Position(msgBuffer.ReadVector3(), player, false);

                                                GetItem(player,msgBuffer.ReadUInt32());
                                            }
                                            break;
                                    }
                                }
                                break;
                        }
                    }
                    catch { }
                }

                //Time to backup map?
                TimeSpan mapUpdateTimeSpan = DateTime.Now - lastMapBackup;
                if (mapUpdateTimeSpan.TotalMinutes > 5)
                {
                    lastMapBackup = DateTime.Now;
                    SaveLevel("autoBK.lvl");
                }

                // Time to send a new server update?
                PublicServerListUpdate(); //It checks for public server / time span

                //Time to terminate finished map sending threads?
                TerminateFinishedThreads();

                // Check for players who are in the zone to deposit.
                VictoryCheck();

                // Is it time to do a lava calculation? If so, do it!
                TimeSpan timeSpan = DateTime.Now - sysTimer;
                if (timeSpan.TotalMilliseconds > 2000)
                {
                    //ConsoleWrite("" + delta);
                    sysTimer = DateTime.Now;

                    //secondflow += 1;

                    //if (secondflow > 2)//every 2nd flow, remove the vacuum that prevent re-spread
                    //{
                    //    EraseVacuum();
                    //    secondflow = 0;
                    //}
                    if (randGen.Next(1, 4) == 3)
                    {
                        bool isUpdateOre = false;
                        bool isUpdateCash = false;
                        for (int a = 1; a < 3; a++)
                        {
                            if (artifactActive[a, 1] > 0)//material artifact
                            {
                                isUpdateOre = true;
                                if (a == 1)
                                {
                                    teamOreRed = teamOreRed + (uint)(10 * artifactActive[a, 1]);
                                }
                                else if (a == 2)
                                {
                                    teamOreBlue = teamOreBlue + (uint)(10 * artifactActive[a, 1]);
                                }

                            }
                            if (artifactActive[a, 5] > 0)//golden artifact
                            {
                                isUpdateCash = true;
                                if (a == 1)
                                {
                                    teamCashRed = teamCashRed + (uint)(2 * artifactActive[a, 5]);
                                }
                                else if (a == 2)
                                {
                                    teamCashBlue = teamCashBlue + (uint)(2 * artifactActive[a, 5]);
                                }

                            }
                        }

                        if (isUpdateOre)
                            foreach (Player p in playerList.Values)
                                SendTeamOreUpdate(p);

                        if(isUpdateCash)
                        foreach (Player p in playerList.Values)
                            SendTeamCashUpdate(p);
                    }
                    foreach (Player p in playerList.Values)//regeneration
                    {
                        if (p.Ping > 0)
                            p.Ping--;

                        if (p.Alive)
                        {
                            if (p.Content[10] == 1)//material artifact personal
                            {
                                if (randGen.Next(1, 4) == 3)
                                {
                                    if (p.Ore < p.OreMax)
                                    {
                                        p.Ore += 10;
                                        if (p.Ore >= p.OreMax)
                                            p.Ore = p.OreMax;

                                        SendOreUpdate(p);
                                    }
                                }
                            }
                            else if (p.Content[10] == 5)//golden artifact personal
                            {
                                if (p.Ore > 99)
                                {
                                    if (p.Weight < p.WeightMax)
                                    {
                                        p.Weight++;
                                        p.Cash += 10;
                                        p.Ore -= 100;
                                        SendCashUpdate(p);
                                        SendWeightUpdate(p);
                                        SendOreUpdate(p);
                                        PlaySound(InfiniminerSound.CashDeposit, p.Position);
                                    }
                                }
                            }
                            else if (p.Content[10] == 6)//storm artifact personal
                            {

                                if(artifactActive[(byte)((p.Team == PlayerTeam.Red) ? PlayerTeam.Blue : PlayerTeam.Red),6] == 0)//stored storm artifact makes team immune
                                foreach (Player pt in playerList.Values)
                                {
                                    if (p.Team != pt.Team && pt.Alive)
                                    {
                                        float distfromPlayer = (p.Position - pt.Position).Length();
                                        if (distfromPlayer < 5)
                                        {
                                            pt.Health -= 5;
                                            if (pt.Health <= 0)
                                            {
                                                Player_Dead(pt,"WAS SHOCKED!");
                                            }
                                            else
                                                SendHealthUpdate(pt);

                                            EffectAtPoint(pt.Position, 1);
                                        }
                                    }
                                }
                            }

                            if (p.Health >= p.HealthMax)
                            {
                                p.Health = p.HealthMax;
                            }
                            else
                            {
                                p.Health = (uint)(p.Health + teamRegeneration[(byte)p.Team]);
                                if (p.Content[10] == 3)//regeneration artifact
                                {
                                    p.Health += 4;
                                }

                                if (p.Health >= p.HealthMax)
                                {
                                    p.Health = p.HealthMax;
                                }
                                SendHealthUpdate(p);
                            }

                            if (p.Class == PlayerClass.Prospector)
                            {
                                if (p.Content[5] == 1)
                                {
                                    p.Content[6]--;
                                    if (p.Content[6] < 1)
                                    {
                                        p.Content[1] = 0;
                                        SendPlayerContentUpdate(p, 1);
                                        p.Content[5] = 0;//sight
                                        SendContentSpecificUpdate(p, 5);
                                        SendPlayerContentUpdate(p, 5);
                                        SendServerMessageToPlayer("Hide must now recharge!", p.NetConn);
                                        EffectAtPoint(p.Position - Vector3.UnitY * 1.5f, 1);
                                    }
                                }
                                else
                                {
                                    if(p.Content[6] < 4)
                                        p.Content[6]++;
                                }
                            }

                            //if (p.Class == PlayerClass.Prospector)//temperature data//giving everyone
                            //{
                            //    p.Content[6] = 0;
                            //    for(int a = -5;a < 6;a++)
                            //        for(int b = -5;b < 6;b++)
                            //            for (int c = -5; c < 6; c++)
                            //            {
                            //                int nx = a + (int)p.Position.X;
                            //                int ny = b + (int)p.Position.Y;
                            //                int nz = c + (int)p.Position.Z;
                            //                if (nx < MAPSIZE - 1 && ny < MAPSIZE - 1 && nz < MAPSIZE - 1 && nx > 0 && ny > 0 && nz > 0)
                            //                {
                            //                    BlockType block = blockList[nx,ny,nz];
                            //                    if (block == BlockType.Lava || block == BlockType.MagmaBurst || block == BlockType.MagmaVent)
                            //                    {
                            //                        p.Content[6] += 5 - Math.Abs(a) + 5 - Math.Abs(b) + 5 - Math.Abs(c);
                            //                    }
                            //                }
                            //            }

                            //    if (p.Content[6] > 0)
                            //        SendContentSpecificUpdate(p, 6);
                            //}
                        }
                    }
                }

                TimeSpan timeSpanZ = DateTime.Now - lastFlowCalcZ;
                serverTime[timeQueue] = DateTime.Now - lastTime;//timeQueue

                timeQueue += 1;
                if (timeQueue > 19)
                    timeQueue = 0;

                lastTime = DateTime.Now;
                delta = (float)((serverTime[0].TotalSeconds + serverTime[1].TotalSeconds + serverTime[2].TotalSeconds + serverTime[3].TotalSeconds + serverTime[4].TotalSeconds + serverTime[5].TotalSeconds + serverTime[6].TotalSeconds + serverTime[7].TotalSeconds + serverTime[8].TotalSeconds + serverTime[9].TotalSeconds + serverTime[10].TotalSeconds + serverTime[11].TotalSeconds + serverTime[12].TotalSeconds + serverTime[13].TotalSeconds + serverTime[14].TotalSeconds + serverTime[15].TotalSeconds + serverTime[16].TotalSeconds + serverTime[17].TotalSeconds + serverTime[18].TotalSeconds + serverTime[19].TotalSeconds) / 20);
                Sunray();
                if (timeSpanZ.TotalMilliseconds > 50)
                {

                    lastFlowCalcZ = DateTime.Now;
                    DoItems();

                }
                //random diamond appearance
                if (sleeping == false)
                if (randGen.Next(1, 100000) == 2)
                {
                    ushort diamondx = (ushort)randGen.Next(4, 57);
                    ushort diamondy = (ushort)randGen.Next(3, 30);
                    ushort diamondz = (ushort)randGen.Next(4, 57);

                    if (blockList[diamondx, diamondy, diamondz] == BlockType.Dirt)
                    {
                       // ConsoleWrite("diamond spawned at " + diamondx + "/" + diamondy + "/" + diamondz);
                        SetBlock(diamondx, diamondy, diamondz, BlockType.Diamond, PlayerTeam.None);
                        blockListHP[diamondx, diamondy, diamondz] = BlockInformation.GetMaxHP(BlockType.Diamond);
                    }
                }
                // Handle console keypresses.
                while (Console.KeyAvailable)
                {
                    ConsoleKeyInfo keyInfo = Console.ReadKey();
                    if (keyInfo.Key == ConsoleKey.Enter)
                    {
                        if (consoleInput.Length > 0)
                            ConsoleProcessInput();
                    }
                    else if (keyInfo.Key == ConsoleKey.Backspace)
                    {
                        if (consoleInput.Length > 0)
                            consoleInput = consoleInput.Substring(0, consoleInput.Length - 1);
                        ConsoleRedraw();
                    }
                    else
                    {
                        consoleInput += keyInfo.KeyChar;
                        ConsoleRedraw();
                    }
                }

                // Is the game over?
                if (winningTeam != PlayerTeam.None && !restartTriggered)
                {
                    BroadcastGameOver();
                    restartTriggered = true;
                    restartTime = DateTime.Now.AddSeconds(10);
                }

                // Restart the server?
                if (restartTriggered && DateTime.Now > restartTime)
                {
                    SaveLevel("autosave_" + (UInt64)DateTime.Now.ToBinary() + ".lvl");

                    netServer.Shutdown("The server is restarting.");

                    Thread.Sleep(100);

                    physics.Abort();
                   // mechanics.Abort();
                    return true;//terminates server thread completely
                }

                // Pass control over to waiting threads.
                if(sleeping == true) {
                    Thread.Sleep(50);
                }
                else
                {
                    Thread.Sleep(1);
                }
            }

            MessageAll("Server going down NOW!");

            netServer.Shutdown("The server was terminated.");
            return false;
        }
Пример #22
0
        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");
        }
Пример #23
0
        protected virtual void Init(int port)
        {
            netConfig = new NetConfiguration("GameApp");
            netConfig.MaxConnections = 128;
            if (MaxConnections != null)
                netConfig.MaxConnections = MaxConnections(this);
            netConfig.Port = port;

            netThread = new Thread(new ThreadStart(Run));
            netThread.Start();
        }
Пример #24
0
        bool colorDirection = true; //increases when true

        #endregion Fields

        #region Constructors

        public PropertyBag(InfiniminerGame gameInstance)
        {
            // Initialize our network device.
            NetConfiguration netConfig = new NetConfiguration("InfiniminerPlus");

            netClient = new NetClient(netConfig);
            netClient.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);

            //netClient.SimulatedMinimumLatency = 0.5f;
            //netClient.SimulatedLatencyVariance = 0.1f;
            //netClient.SimulatedLoss = 0.2f;
            //netClient.SimulatedDuplicates = 0.1f;
            for (int a = 0; a < 50; a++)
            {
                Content[a] = 0;
            }
            artifactActive = new int[3, 20];

            netClient.Start();

            // Initialize engines.
            blockEngine = new BlockEngine(gameInstance);
            interfaceEngine = new InterfaceEngine(gameInstance);
            playerEngine = new PlayerEngine(gameInstance);
            skyplaneEngine = new SkyplaneEngine(gameInstance);
            particleEngine = new ParticleEngine(gameInstance);
            // Create a camera.
            playerCamera = new Camera(gameInstance.GraphicsDevice);

            UpdateCamera();

            // Load sounds.
            if (!gameInstance.NoSound)
            {
                soundList[InfiniminerSound.DigDirt] = gameInstance.Content.Load<SoundEffect>("sounds/dig-dirt");
                soundList[InfiniminerSound.DigMetal] = gameInstance.Content.Load<SoundEffect>("sounds/dig-metal");
                soundList[InfiniminerSound.Ping] = gameInstance.Content.Load<SoundEffect>("sounds/ping");
                soundList[InfiniminerSound.ConstructionGun] = gameInstance.Content.Load<SoundEffect>("sounds/build");
                soundList[InfiniminerSound.Death] = gameInstance.Content.Load<SoundEffect>("sounds/death");
                soundList[InfiniminerSound.CashDeposit] = gameInstance.Content.Load<SoundEffect>("sounds/cash");
                soundList[InfiniminerSound.ClickHigh] = gameInstance.Content.Load<SoundEffect>("sounds/click-loud");
                soundList[InfiniminerSound.ClickLow] = gameInstance.Content.Load<SoundEffect>("sounds/click-quiet");
                soundList[InfiniminerSound.GroundHit] = gameInstance.Content.Load<SoundEffect>("sounds/hitground");
                soundList[InfiniminerSound.Teleporter] = gameInstance.Content.Load<SoundEffect>("sounds/teleport");
                soundList[InfiniminerSound.Jumpblock] = gameInstance.Content.Load<SoundEffect>("sounds/jumpblock");
                soundList[InfiniminerSound.Explosion] = gameInstance.Content.Load<SoundEffect>("sounds/explosion");
                soundList[InfiniminerSound.RadarHigh] = gameInstance.Content.Load<SoundEffect>("sounds/radar-high");
                soundList[InfiniminerSound.RadarLow] = gameInstance.Content.Load<SoundEffect>("sounds/radar-low");
                soundList[InfiniminerSound.RadarSwitch] = gameInstance.Content.Load<SoundEffect>("sounds/switch");
                soundList[InfiniminerSound.RockFall] = gameInstance.Content.Load<SoundEffect>("sounds/rockfall");
            }
        }
Пример #25
0
        public bool Start()
        {
            //Setup the variable toggles
            varBindingsInitialize();

            int tmpMaxPlayers = 16;

            // Read in from the config file.
            DatafileWriter dataFile = new DatafileWriter("server.config.txt");
            if (dataFile.Data.ContainsKey("winningcash"))
                winningCashAmount = uint.Parse(dataFile.Data["winningcash"], System.Globalization.CultureInfo.InvariantCulture);
            if (dataFile.Data.ContainsKey("includelava"))
                includeLava = bool.Parse(dataFile.Data["includelava"]);
            if (dataFile.Data.ContainsKey("orefactor"))
                oreFactor = uint.Parse(dataFile.Data["orefactor"], System.Globalization.CultureInfo.InvariantCulture);
            if (dataFile.Data.ContainsKey("maxplayers"))
                tmpMaxPlayers = (int)Math.Min(32, uint.Parse(dataFile.Data["maxplayers"], System.Globalization.CultureInfo.InvariantCulture));
            if (dataFile.Data.ContainsKey("public"))
                varSet("public", bool.Parse(dataFile.Data["public"]), true);
            if (dataFile.Data.ContainsKey("servername"))
                varSet("name", dataFile.Data["servername"], true);
            if (dataFile.Data.ContainsKey("sandbox"))
                varSet("sandbox", bool.Parse(dataFile.Data["sandbox"]), true);
            if (dataFile.Data.ContainsKey("notnt"))
                varSet("tnt", !bool.Parse(dataFile.Data["notnt"]), true);
            if (dataFile.Data.ContainsKey("sphericaltnt"))
                varSet("stnt", bool.Parse(dataFile.Data["sphericaltnt"]), true);
            if (dataFile.Data.ContainsKey("insanelava"))
                varSet("insanelava", bool.Parse(dataFile.Data["insanelava"]), true);
            if (dataFile.Data.ContainsKey("shockspreadslava"))
                varSet("sspreads", bool.Parse(dataFile.Data["shockspreadslava"]), true);
            if (dataFile.Data.ContainsKey("roadabsorbs"))
                varSet("roadabsorbs", bool.Parse(dataFile.Data["roadabsorbs"]), true);
            if (dataFile.Data.ContainsKey("minelava"))
                varSet("minelava", bool.Parse(dataFile.Data["minelava"]), true);
            if (dataFile.Data.ContainsKey("levelname"))
                levelToLoad = dataFile.Data["levelname"];
            if (dataFile.Data.ContainsKey("greeter"))
                varSet("greeter", dataFile.Data["greeter"],true);

            bool autoannounce = true;
            if (dataFile.Data.ContainsKey("autoannounce"))
                autoannounce = bool.Parse(dataFile.Data["autoannounce"]);

            // Load the ban-list.
            banList = LoadBanList();

            // Load the admin-list
            admins = LoadAdminList();

            if (tmpMaxPlayers>=0)
                varSet("maxplayers", tmpMaxPlayers, true);

            // Initialize the server.
            NetConfiguration netConfig = new NetConfiguration("InfiniminerPlus");
            netConfig.MaxConnections = (int)varGetI("maxplayers");
            netConfig.Port = 5565;
            netServer = new InfiniminerNetServer(netConfig);
            netServer.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true);
            //netServer.SimulatedMinimumLatency = 0.1f;
            //netServer.SimulatedLatencyVariance = 0.05f;
            //netServer.SimulatedLoss = 0.1f;
            //netServer.SimulatedDuplicates = 0.05f;
            netServer.Start();

            // Store the last time that we did a flow calculation.
            DateTime lastFlowCalc = DateTime.Now;
            DateTime lastMapeaterCalc = DateTime.Now;

            //Check if we should autoload a level
            if (dataFile.Data.ContainsKey("autoload") && bool.Parse(dataFile.Data["autoload"]))
            {
                blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE];
                blockCreatorTeam = new PlayerTeam[MAPSIZE, MAPSIZE, MAPSIZE];
                LoadLevel(levelToLoad);
            }
            else
            {
                // Calculate initial lava flows.
                ConsoleWrite("CALCULATING INITIAL LAVA FLOWS");
                ConsoleWrite("TOTAL LAVA BLOCKS = " + newMap());
            }

            //Caculate the shape of spherical tnt explosions
            CalculateExplosionPattern();

            // Send the initial server list update.
            if (autoannounce)
                PublicServerListUpdate(true);

            lastMapBackup = DateTime.Now;
            ServerListener listener = new ServerListener(netServer,this);
            System.Threading.Thread listenerthread = new System.Threading.Thread(new ThreadStart(listener.start));
            listenerthread.Start();
            // Main server loop!
            ConsoleWrite("SERVER READY");
            Random randomizer = new Random(56235676);
            while (keepRunning)
            {

                // Process any messages that are here.

                //Time to backup map?
                TimeSpan mapUpdateTimeSpan = DateTime.Now - lastMapBackup;
                if (mapUpdateTimeSpan.TotalMinutes > 5)
                {
                    System.Threading.Thread backupthread = new System.Threading.Thread(new ThreadStart(BackupLevel));
                    backupthread.Start();
                    lastMapBackup = DateTime.Now;
                }

                // Time to send a new server update?
                PublicServerListUpdate(); //It checks for public server / time span

                //Time to terminate finished map sending threads?
                TerminateFinishedThreads();

                // Check for players who are in the zone to deposit.
                DepositForPlayers();

                // Is it time to do a lava calculation? If so, do it!

                if (varGetB("mapeater"))
                {
                    TimeSpan eaterSpan = DateTime.Now - lastMapeaterCalc;
                    if (eaterSpan.TotalMilliseconds > 500)
                    {
                        lastMapeaterCalc = DateTime.Now;
                        for (int i = 0; i < 200; i++)
                        {
                            ushort x = (ushort)randomizer.Next(0, 64);
                            ushort y = (ushort)randomizer.Next(0, 64);
                            for (ushort z = 62; z > 0; z--)
                            {
                                if (blockList[x, z, y] != BlockType.None)
                                {
                                    SetBlock(x, z, y, BlockType.None, PlayerTeam.None);
                                    break;
                                }
                            }

                        }
                    }

                }
                TimeSpan timeSpan = DateTime.Now - lastFlowCalc;
                if (timeSpan.TotalMilliseconds > 500)
                {
                    DoLavaStuff();
                    lastFlowCalc = DateTime.Now;
                }

                // Handle console keypresses.
                while (Console.KeyAvailable)
                {
                    ConsoleKeyInfo keyInfo = Console.ReadKey();
                    if (keyInfo.Key == ConsoleKey.Enter)
                        ConsoleProcessInput();
                    else if (keyInfo.Key == ConsoleKey.Backspace)
                    {
                        if (consoleInput.Length > 0)
                            consoleInput = consoleInput.Substring(0, consoleInput.Length - 1);
                        ConsoleRedraw();
                    }
                    else
                    {
                        consoleInput += keyInfo.KeyChar;
                        ConsoleRedraw();
                    }
                }

                // Is the game over?
                if (winningTeam != PlayerTeam.None && !restartTriggered)
                {
                    BroadcastGameOver();
                    restartTriggered = true;
                    restartTime = DateTime.Now.AddSeconds(10);
                }

                // Restart the server?
                if (restartTriggered && DateTime.Now > restartTime)
                {
                    SaveLevel("autosave_" + (UInt64)DateTime.Now.ToBinary() + ".lvl");
                    netServer.Shutdown("The server is restarting.");
                    return true;
                }

                // Pass control over to waiting threads.
                Thread.Sleep(1);
            }

            MessageAll("Server going down NOW!");

            netServer.Shutdown("The server was terminated.");
            return false;
        }
Пример #26
0
 /// <summary>
 /// Creates a new NetClient
 /// </summary>
 public NetClient(NetConfiguration config)
     : base(config)
 {
     m_startLock = new object();
 }
Пример #27
0
		public NetPeer(NetConfiguration config)
			: base(config)
		{
			m_allowOutgoingConnections = true;
		}
Пример #28
0
		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");
		}
Пример #29
0
 /// <summary>
 /// Creates a new NetServer
 /// </summary>
 public NetServer(NetConfiguration config)
     : base(config)
 {
     m_connections      = new List <NetConnection>();
     m_connectionLookup = new Dictionary <IPEndPoint, NetConnection>();
 }
Пример #30
0
 public NetPeer(NetConfiguration config)
     : base(config)
 {
     m_allowOutgoingConnections = true;
 }
Пример #31
0
        static void Main(string[] args)
        {
            // create a configuration for the server
            NetConfiguration config = new NetConfiguration("chatApp");
            config.MaxConnections = 128;
            config.Port = 14242;

            // create server and start listening for connections
            NetServer server = new NetServer(config);
            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:
                            Console.WriteLine(buffer.ReadString());
                            break;
                        case NetMessageType.ConnectionApproval:
                            Console.WriteLine("Approval; hail is " + buffer.ReadString());
                            sender.Approve();
                            break;
                        case NetMessageType.StatusChanged:
                            Console.WriteLine("New status for " + sender + ": " + sender.Status + " (" + buffer.ReadString() + ")");
                            break;
                        case NetMessageType.Data:
                            // A client sent this data!
                            string msg = buffer.ReadString();

                            // send to everyone, including sender
                            NetBuffer sendBuffer = server.CreateBuffer();
                            sendBuffer.Write(sender.RemoteEndpoint.ToString() + " wrote: " + msg);

                            // send using ReliableInOrder
                            server.SendToAll(sendBuffer, NetChannel.ReliableInOrder1);
                            break;
                    }
                }

                // User pressed ESC?
                while (Console.KeyAvailable)
                {
                    ConsoleKeyInfo info = Console.ReadKey();
                    if (info.Key == ConsoleKey.Escape)
                        keepRunning = false;
                }

                Thread.Sleep(1);
            }

            server.Shutdown("Application exiting");
        }
Пример #32
0
		static unsafe void Main(string[] args)
		{
			// JIT stuff
			NetBuffer msg = new NetBuffer(20);
			msg.Write((short)short.MaxValue);
			
			// Go
			double timeStart = NetTime.Now;

			msg = new NetBuffer(20);
			for (int n = 0; n < 10000; n++)
			{
				msg.Reset();

				msg.Write((short)short.MaxValue);
				msg.Write((short)short.MinValue);
				msg.Write((short)-42);

				msg.Write(421);
				msg.Write((byte)7);
				msg.Write(-42.8f);

				if (msg.LengthBytes != 15)
					throw new Exception("Bad message length");

				msg.Write("duke of earl");

				int bytesWritten;
				bytesWritten = msg.WriteVariableInt32(-1);
				bytesWritten = msg.WriteVariableInt32(5);
				bytesWritten = msg.WriteVariableInt32(-18);
				bytesWritten = msg.WriteVariableInt32(42);
				bytesWritten = msg.WriteVariableInt32(-420);

				msg.Write((uint)9991);

				// byte boundary kept until here

				msg.Write(true);
				msg.Write((uint)3, 5);
				msg.Write(8.111f);
				msg.Write("again");
				byte[] arr = new byte[] { 1, 6, 12, 24 };
				msg.Write(arr);
				msg.Write((byte)7, 7);
				msg.Write(Int32.MinValue);
				msg.Write(UInt32.MaxValue);
				msg.WriteRangedSingle(21.0f, -10, 50, 12);

				// test reduced bit signed writing
				msg.Write(15, 5);
				msg.Write(2, 5);
				msg.Write(0, 5);
				msg.Write(-1, 5);
				msg.Write(-2, 5);
				msg.Write(-15, 5);

				msg.Write(UInt64.MaxValue);
				msg.Write(Int64.MaxValue);
				msg.Write(Int64.MinValue);

				msg.Write(42);
				msg.WritePadBits();

				int numBits = msg.WriteRangedInteger(0, 10, 5);
				if (numBits != 4)
					throw new Exception("Ack WriteRangedInteger failed");

				// verify
				msg.Position = 0;

				short a = msg.ReadInt16();
				short b = msg.ReadInt16();
				short c = msg.ReadInt16();

				if (a != short.MaxValue || b != short.MinValue || c != -42)
					throw new Exception("Ack thpth short failed");

				if (msg.ReadInt32() != 421)
					throw new Exception("Ack thphth 1");
				if (msg.ReadByte() != (byte)7)
					throw new Exception("Ack thphth 2");
				if (msg.ReadSingle() != -42.8f)
					throw new Exception("Ack thphth 3");
				if (msg.ReadString() != "duke of earl")
					throw new Exception("Ack thphth 4");

				if (msg.ReadVariableInt32() != -1) throw new Exception("ReadVariableInt32 failed 1");
				if (msg.ReadVariableInt32() != 5) throw new Exception("ReadVariableInt32 failed 2");
				if (msg.ReadVariableInt32() != -18) throw new Exception("ReadVariableInt32 failed 3");
				if (msg.ReadVariableInt32() != 42) throw new Exception("ReadVariableInt32 failed 4");
				if (msg.ReadVariableInt32() != -420) throw new Exception("ReadVariableInt32 failed 5");

				if (msg.ReadUInt32() != 9991)
					throw new Exception("Ack thphth 4.5");

				if (msg.ReadBoolean() != true)
					throw new Exception("Ack thphth 5");
				if (msg.ReadUInt32(5) != (uint)3)
					throw new Exception("Ack thphth 6");
				if (msg.ReadSingle() != 8.111f)
					throw new Exception("Ack thphth 7");
				if (msg.ReadString() != "again")
					throw new Exception("Ack thphth 8");
				byte[] rrr = msg.ReadBytes(4);
				if (rrr[0] != arr[0] || rrr[1] != arr[1] || rrr[2] != arr[2] || rrr[3] != arr[3])
					throw new Exception("Ack thphth 9");
				if (msg.ReadByte(7) != 7)
					throw new Exception("Ack thphth 10");
				if (msg.ReadInt32() != Int32.MinValue)
					throw new Exception("Ack thphth 11");
				if (msg.ReadUInt32() != UInt32.MaxValue)
					throw new Exception("Ack thphth 12");

				float v = msg.ReadRangedSingle(-10, 50, 12);
				// v should be close to, but not necessarily exactly, 21.0f
				if ((float)Math.Abs(21.0f - v) > 0.1f)
					throw new Exception("Ack thphth *RangedSingle() failed");

				if (msg.ReadInt32(5) != 15)
					throw new Exception("Ack thphth ReadInt32 1");
				if (msg.ReadInt32(5) != 2)
					throw new Exception("Ack thphth ReadInt32 2");
				if (msg.ReadInt32(5) != 0)
					throw new Exception("Ack thphth ReadInt32 3");
				if (msg.ReadInt32(5) != -1)
					throw new Exception("Ack thphth ReadInt32 4");
				if (msg.ReadInt32(5) != -2)
					throw new Exception("Ack thphth ReadInt32 5");
				if (msg.ReadInt32(5) != -15)
					throw new Exception("Ack thphth ReadInt32 6");

				UInt64 longVal = msg.ReadUInt64();
				if (longVal != UInt64.MaxValue)
					throw new Exception("Ack thphth UInt64");
				if (msg.ReadInt64() != Int64.MaxValue)
					throw new Exception("Ack thphth Int64");
				if (msg.ReadInt64() != Int64.MinValue)
					throw new Exception("Ack thphth Int64");

				if (msg.ReadInt32() != 42)
					throw new Exception("Ack thphth end");

				msg.SkipPadBits();

				if (msg.ReadRangedInteger(0, 10) != 5)
					throw new Exception("Ack thphth ranged integer");
			}

			// test writevariableuint64
			NetBuffer largeBuffer = new NetBuffer(100 * 8);
			UInt64[] largeNumbers = new ulong[100];
			for (int i = 0; i < 100; i++)
			{
				largeNumbers[i] = ((ulong)NetRandom.Instance.NextUInt() << 32) | (ulong)NetRandom.Instance.NextUInt();
				largeBuffer.WriteVariableUInt64(largeNumbers[i]);
			}

			largeBuffer.Position = 0;
			for (int i = 0; i < 100; i++)
			{
				UInt64 ln = largeBuffer.ReadVariableUInt64();
				if (ln != largeNumbers[i])
					throw new Exception("large fail");
			}

			//
			// Extended tests on padbits
			//
			for (int i = 1; i < 31; i++)
			{
				NetBuffer buf = new NetBuffer();
				buf.Write((int)1, i);

				if (buf.LengthBits != i)
					throw new Exception("Bad length!");

				buf.WritePadBits();
				int wholeBytes = buf.LengthBits / 8;
				if (wholeBytes * 8 != buf.LengthBits)
					throw new Exception("WritePadBits failed! Length is " + buf.LengthBits);
			}

			NetBuffer small = new NetBuffer(100);
			byte[] rnd = new byte[24];
			int[] bits = new int[24];
			for (int i = 0; i < 24; i++)
			{
				rnd[i] = (byte)NetRandom.Instance.Next(0, 65);
				bits[i] = NetUtility.BitsToHoldUInt((uint)rnd[i]);

				small.Write(rnd[i], bits[i]);
			}

			small.Position = 0;
			for (int i = 0; i < 24; i++)
			{
				byte got = small.ReadByte(bits[i]);
				if (got != rnd[i])
					throw new Exception("Failed small allocation test");
			}

			double timeEnd = NetTime.Now;
			double timeSpan = timeEnd - timeStart;

			Console.WriteLine("Trivial tests passed in " + (timeSpan * 1000.0) + " milliseconds");

			Console.WriteLine("Creating client and server for live testing...");

			NetConfiguration config = new NetConfiguration("unittest");
			config.Port = 14242;
			NetServer server = new NetServer(config);
			NetBuffer serverBuffer = new NetBuffer();
			server.Start();

			config = new NetConfiguration("unittest");
			NetClient client = new NetClient(config);
			client.SetMessageTypeEnabled(NetMessageType.Receipt, true);
			NetBuffer clientBuffer = client.CreateBuffer();
			client.Start();

			client.Connect("127.0.0.1", 14242);

			List<string> events = new List<string>();

			double end = double.MaxValue;
			double disconnect = double.MaxValue;

			while (NetTime.Now < end)
			{
				double now = NetTime.Now;

				NetMessageType nmt;
				NetConnection sender;

				//
				// client
				//
				if (client.ReadMessage(clientBuffer, out nmt))
				{
					switch (nmt)
					{
						case NetMessageType.StatusChanged:
							Console.WriteLine("Client: " + client.Status + " (" + clientBuffer.ReadString() + ")");
							events.Add("CStatus " + client.Status);
							if (client.Status == NetConnectionStatus.Connected)
							{
								// send reliable message
								NetBuffer buf = client.CreateBuffer();
								buf.Write(true);
								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");
		}
Пример #33
0
		public MyDurableServer(NetConfiguration config)
			: base(config)
		{
		}
Пример #34
0
 /// <summary>
 /// Creates a new NetClient
 /// </summary>
 public NetClient(NetConfiguration config)
     : base(config)
 {
     m_startLock = new object();
 }
Пример #35
0
        public static void setupNetwork()
        {
            NetConfiguration config = new NetConfiguration("apache");

            client = new NetClient(config);
            client.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);
            //client.SetMessageTypeEnabled(NetMessageType.DebugMessage, true);
            //client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
            client.Start();

            // Wait half a second to allow server to start up if run via Visual Studio
            Thread.Sleep(500);

            // Emit discovery signal
            //client.DiscoverLocalServers(14242);
            client.Connect("127.0.0.1", 14242, Encoding.ASCII.GetBytes("Hail from client"));

            Thread.Sleep(500);
        }
Пример #36
0
		static void Main(string[] args)
		{
			// create a client with a default configuration
			NetConfiguration config = new NetConfiguration("chatApp");
			NetClient client = new NetClient(config);
			client.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);
			client.SetMessageTypeEnabled(NetMessageType.DebugMessage, true);
			//client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
			client.Start();

			// Wait half a second to allow server to start up if run via Visual Studio
			Thread.Sleep(500);

			// Emit discovery signal
			client.DiscoverLocalServers(14242);

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

			// current input string
			string input = "";

			// keep running until the user presses a key
			Console.WriteLine("Type 'quit' to exit client");
			Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
			s_keepGoing = true;
			while (s_keepGoing)
			{
				NetMessageType type;

				// check if any messages has been received
				while (client.ReadMessage(buffer, out type))
				{
					switch (type)
					{
						case NetMessageType.ServerDiscovered:
							// just connect to any server found!

							// make hail
							NetBuffer buf = client.CreateBuffer();
							buf.Write("Hail from " + Environment.MachineName);
							client.Connect(buffer.ReadIPEndPoint(), buf.ToArray());
							break;
						case NetMessageType.ConnectionRejected:
							Console.WriteLine("Rejected: " + buffer.ReadString());
							break;
						case NetMessageType.DebugMessage:
						case NetMessageType.VerboseDebugMessage:
							Console.WriteLine(buffer.ReadString());
							break;
						case NetMessageType.StatusChanged:
							string statusMessage = buffer.ReadString();
							NetConnectionStatus newStatus = (NetConnectionStatus)buffer.ReadByte();
							Console.WriteLine("New status: " + newStatus + " (" + statusMessage + ")");
							break;
						case NetMessageType.Data:
							// The server sent this data!
							string msg = buffer.ReadString();
							Console.WriteLine(msg);
							break;
					}
				}

				while (Console.KeyAvailable)
				{
					ConsoleKeyInfo ki = Console.ReadKey();
					if (ki.Key == ConsoleKey.Enter)
					{
						if (!string.IsNullOrEmpty(input))
						{
							if (input == "quit")
							{
								// exit application
								s_keepGoing = false;
							}
							else
							{
								// Send chat message
								NetBuffer sendBuffer = new NetBuffer();
								sendBuffer.Write(input);
								client.SendMessage(sendBuffer, NetChannel.ReliableInOrder1);
								input = "";
							}
						}
					}
					else
					{
						input += ki.KeyChar;
					}
				}

				Thread.Sleep(1);
			}

			client.Shutdown("Application exiting");
		}
Пример #37
0
        static void StartClient()
        {
            Config client_config = Config.Instance;

            // create a client with a default configuration
            NetConfiguration config = new NetConfiguration("EES");

            client_config.Client.connection = new NetClient(config);
            client_config.Client.connection.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);
            client_config.Client.connection.SetMessageTypeEnabled(NetMessageType.DebugMessage, true);
            client_config.Client.connection.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
            client_config.Client.connection.Start();

            // Wait half a second to allow server to start up if run via Visual Studio
            Thread.Sleep(500);

            // Emit discovery signal
            client_config.Client.connection.DiscoverLocalServers(14242);

            // create a buffer to read data into
            NetBuffer buffer = client_config.Client.connection.CreateBuffer();

            // keep running until the user presses a key
            client_config.Client.keep_running = true;
            while (client_config.Client.keep_running)
            {
                NetMessageType type;

                // check if any messages has been received
                while (client_config.Client.connection.ReadMessage(buffer, out type))
                {
                    switch (type)
                    {
                        case NetMessageType.ServerDiscovered:
                            client_config.Client.net_events.fireServerDiscovered(client_config.Client.connection, buffer);
                            break;

                        case NetMessageType.ConnectionRejected:
                            client_config.Client.net_events.fireConnectionRejected(client_config.Client.connection, buffer);
                            break;

                        case NetMessageType.DebugMessage:
                            client_config.Client.net_events.fireDebugMessage(buffer.ReadString());
                            break;

                        case NetMessageType.VerboseDebugMessage:
                            client_config.Client.net_events.fireDebugVerboseMessage(buffer.ReadString());
                            break;

                        case NetMessageType.StatusChanged:
                            client_config.Client.net_events.fireStatusChanged(client_config.Client.connection, buffer);
                            break;

                        case NetMessageType.Data:
                            client_config.Client.net_events.fireDataRecieved(client_config.Client.connection, buffer);
                            break;

                        default:
                            break;
                    }
                }

                Thread.Sleep(1);
            }

            client_config.Client.connection.Shutdown("IOS:master exiting");
        }