/// <summary> /// Starts the network connection with the currnet settings. /// </summary> /// <returns>True if successfull.</returns> public static bool Start() { #if !DEBUG try { #endif if (_isServer == true) { DebugLogger.WriteLog("Setting up server..."); // Load in network configuration file. DebugLogger.WriteLog("Loading network configuration file..."); DebugLogger.IncreaseIndent(); Stream stream = StreamFactory.RequestStream(_networkConfigFile, StreamMode.Open); if (stream == null) return false; XmlDocument document = new XmlDocument(); document.Load(stream); stream.Close(); // Get statistics. _port = Convert.ToInt32(document["network"]["settings"]["port"].InnerText); _maximumClients = Convert.ToInt32(document["network"]["settings"]["maximumclients"].InnerText); _pingDelay = Convert.ToInt32(document["network"]["settings"]["pingdelay"].InnerText); // Load in banned IP's XmlNode bansNode = document["network"]["bans"]; if (bansNode == null) throw new Exception("Network configuration declaration file is missing bans declaration."); foreach (XmlNode subNode in bansNode.ChildNodes) { if (subNode.Name.ToLower() != "ban") continue; NetworkBan ban = new NetworkBan("", 0, DateTime.Now); _bans.Add(ban); foreach (XmlNode subSubNode in subNode.ChildNodes) { switch (subSubNode.Name.ToLower()) { case "ip": ban.IP = subSubNode.InnerText; break; case "accountid": ban.AccountID = Convert.ToInt32(subSubNode.InnerText); break; case "expiration": ban.Expiration = new DateTime(Convert.ToInt64(subSubNode.InnerText)); break; } } DebugLogger.WriteLog("Loaded ban, ip:"+ban.IP+" accountID:" + ban.AccountID); } // Load account details. XmlNode accountsNode = document["network"]["accounts"]; if (accountsNode == null) throw new Exception("Network configuration declaration file is missing accounts declaration."); foreach (XmlNode subNode in accountsNode.ChildNodes) { if (subNode.Name.ToLower() != "account") continue; NetworkAccount account = new NetworkAccount(); _accountList.Add(account); foreach (XmlNode subSubNode in subNode.ChildNodes) { switch (subSubNode.Name.ToLower()) { case "lastknownip": account.LastKnownIP = subSubNode.InnerText; break; case "passwordhash": account.PasswordHash = subSubNode.InnerText; break; case "passwordsalt": account.PasswordSalt = subSubNode.InnerText; break; case "dateregistered": account.DateRegistered = new DateTime(long.Parse(subSubNode.InnerText)); break; case "lastactive": account.LastActive = new DateTime(long.Parse(subSubNode.InnerText)); break; case "username": account.Username = subSubNode.InnerText; break; case "position": account.Position = (NetworkAccountPosition)Enum.Parse(typeof(NetworkAccountPosition), subSubNode.InnerText); break; case "custom": { foreach (XmlNode customNode in subSubNode.ChildNodes) account.CustomSettings[customNode.Name] = customNode.InnerText; break; } } } DebugLogger.WriteLog("Loaded account: " + account.Username); } // Connect to server. DebugLogger.DecreaseIndent(); DebugLogger.WriteLog("Setting up connection..."); _connection = new NetworkConnection(); _connection.Connect("", _port, true); _connection.PacketRecieved += new PacketRecievedEventHandler(OnPacketRecieved); _connection.ClientConnected += new ClientConnectedEventHandler(OnClientConnected); _connection.ClientDisconnected += new ClientDisconnectedEventHandler(OnClientDisconnected); _connection.Disconnected += new DisconnectedEventHandler(OnDisconnected); DebugLogger.WriteLog("Server setup."); return true; } else { DebugLogger.WriteLog("Connecting to server..."); _connection = new NetworkConnection(); _connection.Connect(_serverIP, _port, false); _connection.PacketRecieved += new PacketRecievedEventHandler(OnPacketRecieved); _connection.Disconnected += new DisconnectedEventHandler(OnDisconnected); DebugLogger.WriteLog("Connected to server, waiting for connection result packet."); NetworkPacket packet = _connection.RecievePacket("CONNECTION_RESULT".GetHashCode(), 5000); if (packet != null) { EvaluatePacket(packet); DebugLogger.WriteLog("Connection result packet recieved."); } else { _connection.Close(); _connectionResult = -1; DebugLogger.WriteLog("Connection to server closed, server failed to respond with connection result packet.", BinaryPhoenix.Fusion.Runtime.Debug.LogAlertLevel.Error); return false; } } return true; #if !DEBUG } catch (Exception) { //_isConnected = false; return false; } #endif }
/// <summary> /// Invoked when a client attempts to connect to this server. /// </summary> /// <param name="asyn">Asyncronous state.</param> private void OnClientConnect(IAsyncResult asyn) { if (_socket == null || (_socket.Connected == false && _isListening == false && _isConnected == true)) return; lock (_clientList) { try { Socket clientSocket = _socket.EndAccept(asyn); NetworkConnection clientConnection = new NetworkConnection(clientSocket); // To many clients? if (_clientList.Count >= NetworkManager.MaximumClients) { DebugLogger.WriteLog("Denied connection from " + clientSocket.RemoteEndPoint.ToString() + ", maximum clients already connected."); NetworkPacket banPacket = new NetworkPacket(); banPacket.ID = "CONNECTION_RESULT".GetHashCode(); banPacket[0] = (byte)2; banPacket[1] = (int)0; clientConnection.SendPacket(banPacket); clientSocket.Close(); return; } // Is this IP banned? bool banned = false; string currentIP = clientSocket.RemoteEndPoint.ToString(); if (currentIP.IndexOf(":") >= 0) currentIP = currentIP.Substring(0, currentIP.IndexOf(":")); foreach (NetworkBan ban in NetworkManager.BansList) { if (ban.IsIPBanned(currentIP.ToLower())) { banned = true; break; } } if (banned == true) { DebugLogger.WriteLog("Denied connection from " + clientSocket.RemoteEndPoint.ToString() + ", IP address is banned."); NetworkPacket banPacket = new NetworkPacket(); banPacket.ID = "CONNECTION_RESULT".GetHashCode(); banPacket[0] = (byte)1; banPacket[1] = (int)0; clientConnection.SendPacket(banPacket); clientSocket.Close(); return; } // Work out a new unique ID for this client. int id = 0; while (true) { bool found = false; foreach (NetworkClient subclient in _clientList) if (subclient.ID == id) found = true; if (found == false) break; id++; } // Create a new client object to store details on this connection. NetworkClient client = new NetworkClient(); client.Connection = clientConnection; client.ID = id; _clientList.Add(client); // Ackowledge its existance. NetworkPacket helloPacket = new NetworkPacket(); helloPacket.ID = "CONNECTION_RESULT".GetHashCode(); helloPacket[0] = (byte)0; helloPacket[1] = id; client.Connection.SendPacket(helloPacket); // Log this connection. DebugLogger.WriteLog("Accepted connection from " + clientSocket.RemoteEndPoint.ToString() + ", connection assigned id " + id); // Throw an event. if (ClientConnected != null) ClientConnected(this, client); // Go back to waiting for client connections. _socket.BeginAccept(new AsyncCallback(OnClientConnect), null); } catch (Exception) { return; } } }
public NetworkConnectionScriptObject(NetworkConnection connection) { _nativeObject = connection; }