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); } }
/// <summary> /// Constructor for a server instance /// </summary> public NetServer(NetAppConfiguration config, NetLog log) { NetBase.CurrentContext = this; InitBase(config, log); Connections = new NetConnection[config.MaximumConnections]; m_connectionsLookUpTable = new Dictionary<int, NetConnection>(); }
/// <summary> /// Get IP address from notation (xxx.xxx.xxx.xxx) or hostname /// </summary> public static IPAddress Resolve(NetLog log, string ipOrHost) { if (log == null) throw new ArgumentNullException("log"); if (string.IsNullOrEmpty(ipOrHost)) throw new ArgumentException("Supplied string must not be empty", "ipOrHost"); ipOrHost = ipOrHost.Trim(); if (m_regIP == null) { string expression = "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"; RegexOptions options = RegexOptions.Compiled; m_regIP = new Regex(expression, options); } // is it an ip number string? IPAddress ipAddress = null; if (m_regIP.Match(ipOrHost).Success && IPAddress.TryParse(ipOrHost, out ipAddress)) return ipAddress; // ok must be a host name IPHostEntry entry; try { entry = Dns.GetHostEntry(ipOrHost); if (entry == null) return null; // check each entry for a valid IP address foreach (IPAddress ipCurrent in entry.AddressList) { string sIP = ipCurrent.ToString(); bool isIP = m_regIP.Match(sIP).Success && IPAddress.TryParse(sIP, out ipAddress); if (isIP) break; } if (ipAddress == null) return null; return ipAddress; } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.HostNotFound) { log.Error(string.Format(CultureInfo.InvariantCulture, "Failed to resolve host '{0}'.", ipOrHost)); return null; } else { throw; } } }
public IPlayer(String dns, int port) { NetAppConfiguration myConfig = new NetAppConfiguration("MMO Mahjong"); m_log = new NetLog(); Init(); m_client = new NetClient(myConfig, m_log); m_client.Connect(dns, port); m_client.StatusChanged += new EventHandler<NetStatusEventArgs>(StatusChanged); Application.Idle += new EventHandler(ApplicationLoop); }
/// <summary> /// Dump all statistics to log /// </summary> public void DumpToLog(NetLog log) { if (log == null) { return; } double timespan; if (End == 0.0f) { timespan = NetTime.Now - Start; } else { timespan = End - Start; } log.Debug("--- Statistics for " + m_forConnection + " @ " + NetTime.Now + "--------------"); log.Debug("Timespan: " + timespan + " seconds"); log.Debug("Sent " + PacketsSent + " packets (" + FPS(PacketsSent, timespan) + " per second)"); log.Debug("Sent " + BytesSent + " bytes (" + FPS(BytesSent, timespan) + " per second, " + FPS(BytesSent, (double)PacketsSent) + " per packet, " + FPS(BytesSent, (double)MessagesSent) + " per message)"); log.Debug("Sent " + MessagesSent + " messages (" + FPS(MessagesSent, timespan) + " per second, " + FPS(MessagesSent, (double)PacketsSent) + " per packet)"); int libMessagesSent = MessagesSent - (UserMessagesSent + AckMessagesSent); log.Debug(" ... of which " + UserMessagesSent + " were user messages (" + FPS(UserMessagesSent, timespan) + " per second)"); log.Debug(" ... of which " + AckMessagesSent + " were acknowledge messages (" + FPS(AckMessagesSent, timespan) + " per second)"); log.Debug(" ... of which " + libMessagesSent + " were other system messages (" + FPS(libMessagesSent, timespan) + " per second)"); log.Debug("Received " + PacketsReceived + " packets (" + FPS(PacketsReceived, timespan) + " per second)"); log.Debug("Received " + BytesReceived + " bytes (" + FPS(BytesReceived, timespan) + " per second, " + FPS(BytesReceived, (double)PacketsReceived) + " per packet, " + FPS(BytesReceived, (double)MessagesReceived) + " per message)"); log.Debug("Received " + MessagesReceived + " messages (" + FPS(MessagesReceived, timespan) + " per second, " + FPS(MessagesReceived, (double)PacketsReceived) + " per packet)"); int libMessagesReceived = MessagesReceived - (UserMessagesReceived + AckMessagesReceived); log.Debug(" ... of which " + UserMessagesReceived + " were user messages (" + FPS(UserMessagesReceived, timespan) + " per second)"); log.Debug(" ... of which " + AckMessagesReceived + " were acknowledge messages (" + FPS(AckMessagesReceived, timespan) + " per second)"); log.Debug(" ... of which " + libMessagesReceived + " were other system messages (" + FPS(libMessagesReceived, timespan) + " per second)"); log.Debug("Resent " + MessagesResent + " messages (" + FPS(MessagesResent, timespan) + " per second)"); try { // windows specific stuff IPGlobalProperties ipProps = IPGlobalProperties.GetIPGlobalProperties(); UdpStatistics udpStats = ipProps.GetUdpIPv4Statistics(); log.Debug("System wide datagrams sent: " + (udpStats.DatagramsSent - m_sysSent)); log.Debug("System wide datagrams received: " + (udpStats.DatagramsReceived - m_sysReceived)); } catch (NotSupportedException) { } }
public BBServer() { // Create a log Log = new NetLog(); // Ignore net events of type 'verbose' Log.IgnoreTypes = NetLogEntryTypes.Verbose; // Quiet, you ! // Save log output to this file Log.OutputFileName = "serverlog.html"; // Create the player list PList = new PlayerList(); }
/// <summary> /// Initializes the network engine. /// </summary> /// <param name="strName">The name of the user</param> public SpiderClient(String strName) { spiderName = strName; spiderConfig = new NetAppConfiguration("ymfas",DEFAULT_PORT); spiderLog = new NetLog(); spiderLog.OutputFileName = "YMFAS Net Log (Port " + DEFAULT_PORT + ").html"; localSessionQueue = new Queue(50); messageQueue = new Queue(50); disconnectQueue = new Queue(50); spiderNet = new NetClient(spiderConfig,spiderLog); }
/// <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(); }
/// <summary> /// Dump all statistics for this connection to the log specified /// </summary> public void DumpStatisticsToLog(NetLog log) { Statistics.DumpToLog(log); for (int i = 0; i < NetConstants.NumSequenceChannels; i++) { NetChannel channel = (NetChannel)i; if (m_savedReliableMessages[i] != null && m_savedReliableMessages[i].Count > 0) { log.Debug("Saved reliable messages left in " + channel + ": " + m_savedReliableMessages[i].Count); foreach (NetMessage mmm in m_savedReliableMessages[i]) { log.Debug("... " + mmm + " - next resend time: " + mmm.m_nextResendTime + " numresends: " + mmm.m_numResends); } } } log.Debug("Unsent acknowledges: " + m_unsentAcknowledges.Count); log.Debug("Withheld messages: " + m_withheldMessages.Count); log.Flush(); }
public Program() { NetAppConfiguration myConfig = new NetAppConfiguration("MMO Mahjong", 14242); NetLog log = new NetLog(); NetClient Client = new NetClient(myConfig, log); Client.Connect("localhost", 14242); // takes IP number or hostnameHow to detect connects/disconnects Client.StatusChanged += new EventHandler<NetStatusEventArgs>(StatusChanged);// to track connect/disconnect etc bool keepGoing = true; while (keepGoing) { Client.Heartbeat(); NetMessage msg; while ((msg = Client.ReadMessage()) != null) { string str = msg.ReadString(); // <- for example System.Console.WriteLine("You got a packet containing: " + str); Thread.Sleep(1); } } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //PList = new PlayerList(); MainForm = new ChatForm(); AppConfig = new Configuration(); IsAppHidden = AppConfig.RunMinimized; // Create a configuration for the client Program.ChatApplicationBusiness.Config = new NetAppConfiguration("BBTcpTest"); Program.BBBotBusiness = new BBBotBusiness(Program.ChatApplicationBusiness); // enable encryption; this key was generated using the 'GenerateEncryptionKeys' application Config.EnableEncryption( "AQABwV1rQ1NDWzkkhUsYtMiRGjyxSn/zI13tros2RlXHlW6PA7Cvw2nOyMhDmweM+" + "T/+FWzssAWLh8qd+YHaMCCFskVdaZfRzquZlNOs9mX/vtxkLrXgBUaJQD/XOuBeJF" + "o3RfAKA4uhrEr7Bk1iB3zJQW1bSHK7KmmEWzMErk6iA7c=", null); Log = new NetLog(); Log.IgnoreTypes = NetLogEntryTypes.Verbose; // Verbose; Log.IsOutputToFileEnabled = false; Log.OutputFileName = "clientlog.html"; // uncomment this if you want to start multiple instances of this process on the same computer //Log.OutputFileName = "clientlog" + System.Diagnostics.Process.GetCurrentProcess().Id + ".html"; //Log.LogEvent += new EventHandler<NetLogEventArgs>(Log_LogEvent); Client = new NetClient(Config, Log); Client.StatusChanged += new EventHandler<NetStatusEventArgs>(Client_StatusChanged); Application.Idle += new EventHandler(ApplicationLoop); //MainForm.TypingStateChanged += new EventHandler<ChatForm.TypingEvent>(MainForm_TypingStateChanged); CreateNotificationIcon(); Application.Run(MainForm); if (Client != null) Client.Shutdown("Application exiting"); if (notifyIconNA != null) notifyIconNA.Visible = false; }
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); }
public void ClientClicked() { this.Window.Title = "Trying To Connect...."; //Since this is a client we dont have to specify a port here nac = new NetAppConfiguration("ZombieSim"); Log = new NetLog(); //Im Using this to show how to log files, So we pick that we want //to ignore nothing, Change this depending on what your //wanting to log for various debugging. Log.IgnoreTypes = NetLogEntryTypes.None; //Specify if you want to enable output to a file which we do. Log.IsOutputToFileEnabled = true; //If we output to a file we have to pick a filename to output it to. Log.OutputFileName = "Client.html"; //We Initiate the client here, it has not connected to the server yet. client = new NetClient(nac, Log); //We Want to Log Events that are fired from the client client.StatusChanged += new EventHandler<NetStatusEventArgs>(client_StatusChanged); //Finally we connect to the server, Specify the IP Address and //port if your wanting to connect to xxx.xxx.xxx.xxx //we would change this line to "192.168.1.1",12345 client.Connect("192.168.0.200", 12345); }
public NetClient(NetAppConfiguration config, NetLog log) { NetBase.CurrentContext = this; InitBase(config, log); }
protected void InitBase(NetAppConfiguration config, NetLog log) { if (config == null) throw new ArgumentNullException("config"); if (log == null) throw new ArgumentNullException("log"); IsLittleEndian = BitConverter.IsLittleEndian; //if (BitConverter.IsLittleEndian) BitWriter = new LittleEndianBitWriter(); //else // BitWriter = new BigEndianBitWriter(); Configuration = config; Log = log; Configuration.m_isLocked = true; // prevent changes // validate config if (config.ApplicationIdentifier == NetConstants.DefaultApplicationIdentifier) log.Error("Warning! ApplicationIdentifier not set in configuration!"); if (this is NetServer) { if (config.MaximumConnections == -1) throw new ArgumentException("MaximumConnections must be set in configuration!"); if (config.ServerName == NetConstants.DefaultServerName) log.Warning("Warning! Server name not set!"); } // create buffers m_sendBuffer = new NetBuffer(config.SendBufferSize); m_receiveBuffer = new NetBuffer(config.ReceiveBufferSize); // Bind to port try { IPEndPoint iep = new IPEndPoint(IPAddress.Any, config.Port); EndPoint ep = (EndPoint)iep; m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); m_socket.Blocking = false; m_socket.Bind(ep); if (iep.Port != 0) Log.Info("Bound to port " + iep.Port); } catch (SocketException sex) { if (sex.SocketErrorCode != SocketError.AddressAlreadyInUse) throw new NetException("Failed to bind to port " + config.Port + " - Address already in use!", sex); } catch (Exception ex) { throw new NetException("Failed to bind to port " + config.Port, ex); } m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, config.ReceiveBufferSize); m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, config.SendBufferSize); m_senderRemote = (EndPoint)new IPEndPoint(IPAddress.Any, 0); #if DEBUG m_lagLoss = new NetLogLossInducer(log); #endif return; }
/// <summary> /// Dump all statistics for this connection to the log specified /// </summary> public void DumpStatisticsToLog(NetLog log) { Statistics.DumpToLog(log); for(int i=0;i<NetConstants.NumSequenceChannels;i++) { NetChannel channel = (NetChannel)i; if (m_savedReliableMessages[i] != null && m_savedReliableMessages[i].Count > 0) { log.Debug("Saved reliable messages left in " + channel + ": " + m_savedReliableMessages[i].Count); foreach (NetMessage mmm in m_savedReliableMessages[i]) { log.Debug("... " + mmm + " - next resend time: " + mmm.m_nextResendTime + " numresends: " + mmm.m_numResends); } } } log.Debug("Unsent acknowledges: " + m_unsentAcknowledges.Count); log.Debug("Withheld messages: " + m_withheldMessages.Count); log.Flush(); }
public NetLogLossInducer(NetLog log) { m_log = log; m_delayed = new List<DelayedPacket>(); }
/// <summary> /// Get IP address from notation (xxx.xxx.xxx.xxx) or hostname /// </summary> public static IPAddress Resolve(NetLog log, string ipOrHost) { if (log == null) { throw new ArgumentNullException("log"); } if (string.IsNullOrEmpty(ipOrHost)) { throw new ArgumentException("Supplied string must not be empty", "ipOrHost"); } ipOrHost = ipOrHost.Trim(); if (m_regIP == null) { string expression = "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"; RegexOptions options = RegexOptions.Compiled; m_regIP = new Regex(expression, options); } // is it an ip number string? IPAddress ipAddress = null; if (m_regIP.Match(ipOrHost).Success&& IPAddress.TryParse(ipOrHost, out ipAddress)) { return(ipAddress); } // ok must be a host name IPHostEntry entry; try { entry = Dns.GetHostEntry(ipOrHost); if (entry == null) { return(null); } // check each entry for a valid IP address foreach (IPAddress ipCurrent in entry.AddressList) { string sIP = ipCurrent.ToString(); bool isIP = m_regIP.Match(sIP).Success&& IPAddress.TryParse(sIP, out ipAddress); if (isIP) { break; } } if (ipAddress == null) { return(null); } return(ipAddress); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.HostNotFound) { log.Error(string.Format(CultureInfo.InvariantCulture, "Failed to resolve host '{0}'.", ipOrHost)); return(null); } else { throw; } } }
public NetLogLossInducer(NetLog log) { m_log = log; m_delayed = new List <DelayedPacket>(); }
protected void InitBase(NetAppConfiguration config, NetLog log) { if (config == null) { throw new ArgumentNullException("config"); } if (log == null) { throw new ArgumentNullException("log"); } IsLittleEndian = BitConverter.IsLittleEndian; //if (BitConverter.IsLittleEndian) BitWriter = new LittleEndianBitWriter(); //else // BitWriter = new BigEndianBitWriter(); Configuration = config; Log = log; Configuration.m_isLocked = true; // prevent changes // validate config if (config.ApplicationIdentifier == NetConstants.DefaultApplicationIdentifier) { log.Error("Warning! ApplicationIdentifier not set in configuration!"); } if (this is NetServer) { if (config.MaximumConnections == -1) { throw new ArgumentException("MaximumConnections must be set in configuration!"); } if (config.ServerName == NetConstants.DefaultServerName) { log.Warning("Warning! Server name not set!"); } } // create buffers m_sendBuffer = new NetBuffer(config.SendBufferSize); m_receiveBuffer = new NetBuffer(config.ReceiveBufferSize); // Bind to port try { IPEndPoint iep = new IPEndPoint(IPAddress.Any, config.Port); EndPoint ep = (EndPoint)iep; m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); m_socket.Blocking = false; m_socket.Bind(ep); if (iep.Port != 0) { Log.Info("Bound to port " + iep.Port); } } catch (SocketException sex) { if (sex.SocketErrorCode != SocketError.AddressAlreadyInUse) { throw new NetException("Failed to bind to port " + config.Port + " - Address already in use!", sex); } } catch (Exception ex) { throw new NetException("Failed to bind to port " + config.Port, ex); } m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, config.ReceiveBufferSize); m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, config.SendBufferSize); m_senderRemote = (EndPoint) new IPEndPoint(IPAddress.Any, 0); #if DEBUG m_lagLoss = new NetLogLossInducer(log); #endif return; }
/// <summary> /// Dump all statistics to log /// </summary> public void DumpToLog(NetLog log) { if (log == null) return; double timespan; if (End == 0.0f) timespan = NetTime.Now - Start; else timespan = End - Start; log.Debug("--- Statistics for " + m_forConnection + " @ " + NetTime.Now + "--------------"); log.Debug("Timespan: " + timespan + " seconds"); log.Debug("Sent " + PacketsSent + " packets (" + FPS(PacketsSent, timespan) + " per second)"); log.Debug("Sent " + BytesSent + " bytes (" + FPS(BytesSent, timespan) + " per second, " + FPS(BytesSent, (double)PacketsSent) + " per packet, " + FPS(BytesSent, (double)MessagesSent) + " per message)"); log.Debug("Sent " + MessagesSent + " messages (" + FPS(MessagesSent, timespan) + " per second, " + FPS(MessagesSent, (double)PacketsSent) + " per packet)"); int libMessagesSent = MessagesSent - (UserMessagesSent + AckMessagesSent); log.Debug(" ... of which " + UserMessagesSent + " were user messages (" + FPS(UserMessagesSent, timespan) + " per second)"); log.Debug(" ... of which " + AckMessagesSent + " were acknowledge messages (" + FPS(AckMessagesSent, timespan) + " per second)"); log.Debug(" ... of which " + libMessagesSent + " were other system messages (" + FPS(libMessagesSent, timespan) + " per second)"); log.Debug("Received " + PacketsReceived + " packets (" + FPS(PacketsReceived, timespan) + " per second)"); log.Debug("Received " + BytesReceived + " bytes (" + FPS(BytesReceived, timespan) + " per second, " + FPS(BytesReceived, (double)PacketsReceived) + " per packet, " + FPS(BytesReceived, (double)MessagesReceived) + " per message)"); log.Debug("Received " + MessagesReceived + " messages (" + FPS(MessagesReceived, timespan) + " per second, " + FPS(MessagesReceived, (double)PacketsReceived) + " per packet)"); int libMessagesReceived = MessagesReceived - (UserMessagesReceived + AckMessagesReceived); log.Debug(" ... of which " + UserMessagesReceived + " were user messages (" + FPS(UserMessagesReceived, timespan) + " per second)"); log.Debug(" ... of which " + AckMessagesReceived + " were acknowledge messages (" + FPS(AckMessagesReceived, timespan) + " per second)"); log.Debug(" ... of which " + libMessagesReceived + " were other system messages (" + FPS(libMessagesReceived, timespan) + " per second)"); log.Debug("Resent " + MessagesResent + " messages (" + FPS(MessagesResent, timespan) + " per second)"); try { // windows specific stuff IPGlobalProperties ipProps = IPGlobalProperties.GetIPGlobalProperties(); UdpStatistics udpStats = ipProps.GetUdpIPv4Statistics(); log.Debug("System wide datagrams sent: " + (udpStats.DatagramsSent - m_sysSent)); log.Debug("System wide datagrams received: " + (udpStats.DatagramsReceived - m_sysReceived)); } catch (NotSupportedException) { } }