Beispiel #1
0
        MMOServer(int port)
        {
            m_plugin = new Plugin(Environment.CurrentDirectory);

            Init();
            NetAppConfiguration config = new NetAppConfiguration("MMO Mahjong", port);
            config.MaximumConnections = 128;
            config.Port = port;
            config.ServerName = Environment.MachineName + " server";

            m_log = new NetLog();
            m_log.IgnoreTypes = NetLogEntryTypes.None;
            m_log.LogEvent += new EventHandler<NetLogEventArgs>(OnLogEvent);

            Server = new NetServer(config, m_log);
            Server.StatusChanged += new EventHandler<NetStatusEventArgs>(OnStatusChange);

            Server.ConnectionRequest += new EventHandler<NetConnectRequestEventArgs>(OnConnectionRequest);

            while (true)
            {
                Server.Heartbeat();

                NetMessage msg;
                while ((msg = Server.ReadMessage()) != null)
                    HandleMessage(msg);

                System.Threading.Thread.Sleep(1);
            }
        }
Beispiel #2
0
        public static NetMessage EncodeResponse(NetServer server)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            NetMessage msg = new NetMessage(server.Configuration.ServerName.Length + 4);

            msg.m_type = NetMessageType.Discovery;
            msg.Write((ushort)server.NumConnected);
            msg.Write((ushort)server.Configuration.MaximumConnections);
            msg.Write((string)server.Configuration.ServerName);
            return(msg);
        }
Beispiel #3
0
        /// <summary>
        /// Initializes the network engine.
        /// </summary>
        /// <param name="type">Client or Server</param>
        /// <param name="strName">The name of the user</param>
        public SpiderServer(String strName)
        {
            spiderName = strName;
            spiderConfig = new NetAppConfiguration("ymfas",DEFAULT_PORT);
            spiderLog = new NetLog();
            spiderLog.OutputFileName = "YMFAS Net Log (Port 30803).html";
            messageQueue = new Queue(50);
            disconnectQueue = new Queue(50);

            spiderConfig.MaximumConnections = MAX_CONNECTIONS;
            spiderConfig.ServerName = spiderName + "'s Game";
            spiderNet = new NetServer(spiderConfig,spiderLog);
            spiderNet.StatusChanged += new EventHandler<NetStatusEventArgs>(SpiderNet_StatusChangedHandler);
            clients = new ArrayList();
        }
 public void HostClicked()
 {
     this.Window.Title = "Hosting....";
     nac = new NetAppConfiguration("ZombieSim", 12345);
     nac.MaximumConnections = 32;
     nac.ServerName = "ZombieSim!";
     Log = new NetLog();
     server = new NetServer(nac, Log);
     server.StatusChanged += new
         EventHandler<NetStatusEventArgs>(server_StatusChanged);
 }
Beispiel #5
0
        internal static void HandleConnect(NetMessage connectMsg, NetServer server, IPEndPoint senderEndpoint)
        {
            NetMessage response;

            if (server.NumConnected >= server.Configuration.MaximumConnections)
            {
                // server full
                response = new NetMessage(NetMessageType.Handshake, "Server full".Length + 1);
                response.Write((byte)NetHandshakeType.Disconnected);
                response.Write("Server full");
                server.SendSingleMessageAtOnce(response, null, senderEndpoint);
                return;
            }

            ushort remoteNow = connectMsg.ReadUInt16();
            //server.Log.Debug("Setting remote clock based on guess of 50 ms lag...");
            int remoteClockOffset = NetTime.CalculateOffset(NetTime.Now, remoteNow, 0.05);             // assume 50ms...

            // read symmetric key
            int encSymKeyLen = connectMsg.ReadUInt16();

            byte[] encSymKey = null;
            if (encSymKeyLen > 0)
            {
                encSymKey = connectMsg.ReadBytes(encSymKeyLen);
            }

            // read custom data
            int cdLen = (int)connectMsg.Read7BitEncodedUInt();

            byte[] customData = null;
            if (cdLen > 0)
            {
                customData = connectMsg.ReadBytes(cdLen);
            }

            string failReason = null;
            bool   ok         = server.ApproveConnection(senderEndpoint, customData, out failReason);

            if (!ok)
            {
                if (!string.IsNullOrEmpty(failReason))
                {
                    // send disconnect reason; unencrypted, client can handle it because status is connecting
                    response = new NetMessage(NetMessageType.Handshake, failReason.Length + 3);
                    response.Write((byte)NetHandshakeType.Disconnected);
                    response.Write(failReason);
                    server.SendSingleMessageAtOnce(response, null, senderEndpoint);
                }

                // connection not approved
                return;
            }

            NetConnection connection = server.AddConnection(senderEndpoint, remoteClockOffset);

            if (connection == null)
            {
                return;                 // uh oh
            }
            if (encSymKeyLen > 0)
            {
                byte[] symKey = connection.m_encryption.DecryptRSA(encSymKey);
                if (symKey == null)
                {
                    // send disconnect unencrypted, client can handle it because status is connecting
                    string bye = "RSA failed; are you using correct public key?";
                    response = new NetMessage(NetMessageType.Handshake, bye.Length + 3);
                    response.Write((byte)NetHandshakeType.Disconnected);
                    response.Write(bye);
                    server.SendSingleMessageAtOnce(response, null, senderEndpoint);

                    server.Log.Warning("Failed to decrypt RSA encrypted symmetric key from " + senderEndpoint);
                    return;
                }
                connection.m_encryption.SetSymmetricKey(symKey);

                server.Log.Debug("Received Connect containing key: " + Convert.ToBase64String(symKey));
            }
            else
            {
                if (server.Configuration.UsesEncryption)
                {
                    server.Log.Warning("Client tried to connect without encryption from " + senderEndpoint);

                    // denied
                    response = new NetMessage(NetMessageType.Handshake, "Encryption required".Length + 1);
                    response.Write((byte)NetHandshakeType.Disconnected);
                    response.Write("Encryption required");
                    server.SendSingleMessageAtOnce(response, null, senderEndpoint);
                    return;
                }
                server.Log.Debug("Received Connect - using unencrypted connection!");
            }

            // send connect response
            int bytesSent = SendConnectResponse(server, connection, senderEndpoint);

            if (connection != null)
            {
                // account for connectresponse
                connection.Statistics.PacketsSent++;
                connection.Statistics.MessagesSent++;
                connection.Statistics.BytesSent += bytesSent;
            }
        }
Beispiel #6
0
      public void StartServer(int Port)
      {
         // Create a configuration for the server
         // 'SimpleChat' is our application identifier, which distinguishes it from other
         // lidgren.library.network applications
         // 14242 is the port the server listens on; ie. the port clients should connect to
         Config = new NetAppConfiguration("BBTcpTest", Port);

         // set maximum number of clients to 128
         Config.MaximumConnections = 128;

         // set a server name (which shows up when client discovers local servers)
         Config.ServerName = "BB Tcp Test Server";

         // enable encryption; this key was generated using the 'GenerateEncryptionKeys' application
         Config.EnableEncryption(
              "AQABwV1rQ1NDWzkkhUsYtMiRGjyxSn/zI13tros2RlXHlW6PA7Cvw2nOyMhDmweM+" +
              "T/+FWzssAWLh8qd+YHaMCCFskVdaZfRzquZlNOs9mX/vtxkLrXgBUaJQD/XOuBeJF" +
              "o3RfAKA4uhrEr7Bk1iB3zJQW1bSHK7KmmEWzMErk6iA7c=",
              "R6Gp2LkBnMugYdieAGrEhimxq92WXqWvJRfhNVEVrJ/WTxGnKwcJWYwGr2muqa8xG" +
              "xLM47BKLjW7K/EUuPtzSx8cGCDG1ET+5C984lu+pxb1XTHhz4qWpfS8Ti7BV4472F" +
              "wK9y/SxVew19rXNvYLD4aZrVOel+UV8a+3SJTGYXGyEX0OqmoaH0KPfGH5nGLOXcm" +
              "ZHy8yarV193X+bwQL8zxMbNk2UntbLg4m5+t2XyPY2cexDLLCWPviqbF4ZbLJO8xs" +
              "uni1H2QJZ9wn61fNhOQBkoI8YfYYah257zYDVCBgpDFPYXH5LaWfhevV3534Sz4Cw" +
              "D7r6m5aCD0Tsx9pDfsa81VyaJO37kpMTK7HvNtGv5GXwWTNNGwUQTfRIDE06RmLvv" +
              "zyC5YCT40Nqwjz5/dN4Qgb/dAUvsQYn3zsZNj7lfzurcLxGG4x0aCOVafeAb5oRHr" +
              "4VthHVNjymDmiPaiZyP8fmX10M+3hl1o/LDf71jEW+MqPiMgoYpGDEccFxMHtodV6" +
              "Yndv/z+4iFZ76K3Z/QQFgOSaVoAdx2VjlaCXaX6Kywng/pIf3mumy5WubTnjcdG7f" +
              "J+ImyVzs9lkiw==");

         // Now create the server!
         Server = new NetServer(Config, Log);

         //// catch clients connecting
         //ServerBB.Server = Program.Server;
         //Server.ConnectionRequest += new EventHandler<NetConnectRequestEventArgs>(Program.Server_ConnectionRequest);

         // catch status changes; for example, when a client connects or disconnects
         Server.StatusChanged += new EventHandler<NetStatusEventArgs>(this.Server_StatusChanged);
      }
		internal static void HandleConnect(NetMessage connectMsg, NetServer server, IPEndPoint senderEndpoint)
		{
			NetMessage response;
			if (server.NumConnected >= server.Configuration.MaximumConnections)
			{
				// server full
				response = new NetMessage(NetMessageType.Handshake, "Server full".Length + 1);
				response.Write((byte)NetHandshakeType.Disconnected);
				response.Write("Server full");
				server.SendSingleMessageAtOnce(response, null, senderEndpoint);
				return;
			}

			ushort remoteNow = connectMsg.ReadUInt16();
			//server.Log.Debug("Setting remote clock based on guess of 50 ms lag...");
			int remoteClockOffset = NetTime.CalculateOffset(NetTime.Now, remoteNow, 0.05); // assume 50ms...
			
			// read symmetric key
			int encSymKeyLen = connectMsg.ReadUInt16();
			byte[] encSymKey = null;
			if (encSymKeyLen > 0)
				encSymKey = connectMsg.ReadBytes(encSymKeyLen);

			// read custom data
			int cdLen = (int)connectMsg.Read7BitEncodedUInt();
			byte[] customData = null;
			if (cdLen > 0)
				customData = connectMsg.ReadBytes(cdLen);

			string failReason = null;
			bool ok = server.ApproveConnection(senderEndpoint, customData, out failReason);
			if (!ok)
			{
				if (!string.IsNullOrEmpty(failReason))
				{
					// send disconnect reason; unencrypted, client can handle it because status is connecting
					response = new NetMessage(NetMessageType.Handshake, failReason.Length + 3);
					response.Write((byte)NetHandshakeType.Disconnected);
					response.Write(failReason);
					server.SendSingleMessageAtOnce(response, null, senderEndpoint);
				}

				// connection not approved
				return;
			}

			NetConnection connection = server.AddConnection(senderEndpoint, remoteClockOffset);
			if (connection == null)
				return; // uh oh 

			if (encSymKeyLen > 0)
			{
				byte[] symKey = connection.m_encryption.DecryptRSA(encSymKey);
				if (symKey == null)
				{
					// send disconnect unencrypted, client can handle it because status is connecting
					string bye = "RSA failed; are you using correct public key?";
					response = new NetMessage(NetMessageType.Handshake, bye.Length + 3);
					response.Write((byte)NetHandshakeType.Disconnected);
					response.Write(bye);
					server.SendSingleMessageAtOnce(response, null, senderEndpoint);

					server.Log.Warning("Failed to decrypt RSA encrypted symmetric key from " + senderEndpoint);
					return;
				}
				connection.m_encryption.SetSymmetricKey(symKey);

				server.Log.Debug("Received Connect containing key: " + Convert.ToBase64String(symKey));
			}
			else
			{
				if (server.Configuration.UsesEncryption)
				{
					server.Log.Warning("Client tried to connect without encryption from " + senderEndpoint);

					// denied
					response = new NetMessage(NetMessageType.Handshake, "Encryption required".Length + 1);
					response.Write((byte)NetHandshakeType.Disconnected);
					response.Write("Encryption required");
					server.SendSingleMessageAtOnce(response, null, senderEndpoint);
					return;
				}
				server.Log.Debug("Received Connect - using unencrypted connection!");
			}

			// send connect response
			int bytesSent = SendConnectResponse(server, connection, senderEndpoint);

			if (connection != null)
			{
				// account for connectresponse
				connection.Statistics.PacketsSent++;
				connection.Statistics.MessagesSent++;
				connection.Statistics.BytesSent += bytesSent;
			}
		}
		public static NetMessage EncodeResponse(NetServer server)
		{
			if (server == null)
				throw new ArgumentNullException("server");
			NetMessage msg = new NetMessage(server.Configuration.ServerName.Length + 4);
			msg.m_type = NetMessageType.Discovery;
			msg.Write((ushort)server.NumConnected);
			msg.Write((ushort)server.Configuration.MaximumConnections);
			msg.Write((string)server.Configuration.ServerName);
			return msg;
		}