Reformatting/refactoring code

feature-npv2
Icedream 2014-05-30 20:27:58 +02:00
parent 11486ab8e4
commit 1c990f841b
21 changed files with 79 additions and 75 deletions

View File

@ -1,12 +1,12 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using log4net; using log4net;
using NPSharp.Master.Messages.Data; using NPSharp.Master.Data;
namespace NPSharp.Master.Messages.Client namespace NPSharp.Master.Messages.Client
{ {
/// <summary> /// <summary>
/// Represents a request message for the master server for a standard dedicated server list. /// Represents a request message for the master server for a standard dedicated server list.
/// </summary> /// </summary>
[MasterClientMessage("getservers")] [MasterClientMessage("getservers")]
public class MasterGetServersMessage : MasterClientMessage public class MasterGetServersMessage : MasterClientMessage
@ -18,10 +18,26 @@ namespace NPSharp.Master.Messages.Client
Log = LogManager.GetLogger(typeof (MasterGetServersMessage)); Log = LogManager.GetLogger(typeof (MasterGetServersMessage));
} }
/// <summary>
/// The game for which servers should be fetched
/// </summary>
public string GameName { get; set; }
/// <summary>
/// The protocol version of the dedicated servers to search for
/// </summary>
public uint ProtocolVersion { get; set; }
/// <summary>
/// Extra keywords to take care of when generating the server list
/// </summary>
public List<MasterGetServersKeywords> Keywords { get; set; }
protected override string Serialize() protected override string Serialize()
{ {
// I wonder if an extra useless space char at the end is okay in this case // I wonder if an extra useless space char at the end is okay in this case
return string.Format("{0} {1} {2} {3}", Name, GameName, ProtocolVersion, string.Join(" ", Keywords.Select(k => k.ToString()))); return string.Format("{0} {1} {2} {3}", Name, GameName, ProtocolVersion,
string.Join(" ", Keywords.Select(k => k.ToString())));
} }
protected override void Deserialize(string[] arguments) protected override void Deserialize(string[] arguments)
@ -44,20 +60,5 @@ namespace NPSharp.Master.Messages.Client
} }
} }
} }
/// <summary>
/// The game for which servers should be fetched
/// </summary>
public string GameName { get; set; }
/// <summary>
/// The protocol version of the dedicated servers to search for
/// </summary>
public uint ProtocolVersion { get; set; }
/// <summary>
/// Extra keywords to take care of when generating the server list
/// </summary>
public List<MasterGetServersKeywords> Keywords { get; set; }
} }
} }

View File

@ -1,7 +1,7 @@
namespace NPSharp.Master.Messages.Data namespace NPSharp.Master.Data
{ {
/// <summary> /// <summary>
/// Represents keywords for a master server standard serverlist request. /// Represents keywords for a master server standard serverlist request.
/// </summary> /// </summary>
public enum MasterGetServersKeywords public enum MasterGetServersKeywords
{ {

View File

@ -25,7 +25,8 @@ namespace NPSharp.Master
var buffer = new List<byte>(); var buffer = new List<byte>();
if (standardFormat) if (standardFormat)
buffer.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(IP.GetHashCode()))); // TODO: GetHashCode == IP address as number??? buffer.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(IP.GetHashCode())));
// TODO: GetHashCode == IP address as number???
else else
{ {
// TODO: Implement extended serialization format for IP addresses! // TODO: Implement extended serialization format for IP addresses!

View File

@ -71,7 +71,7 @@ namespace NPSharp.Master.Messages
{ {
var header = buffer.Take(4).ToArray(); var header = buffer.Take(4).ToArray();
var command = Encoding.ASCII.GetString(buffer, 4, buffer.Length - 4).Trim(); var command = Encoding.ASCII.GetString(buffer, 4, buffer.Length - 4).Trim();
var commandSplit = command.Split(new[] { '\t', '\r', '\n', '\0', ' ' }, var commandSplit = command.Split(new[] {'\t', '\r', '\n', '\0', ' '},
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
var commandName = commandSplit[0]; var commandName = commandSplit[0];
@ -79,11 +79,11 @@ namespace NPSharp.Master.Messages
// Search for a message class which fits to the commandName // Search for a message class which fits to the commandName
var message = var message =
(MasterClientMessage)Activator.CreateInstance(Assembly.GetExecutingAssembly() (MasterClientMessage) Activator.CreateInstance(Assembly.GetExecutingAssembly()
.GetTypes() .GetTypes()
.Single( .Single(
t => t =>
t.IsSubclassOf(typeof(MasterClientMessage)) && t.IsSubclassOf(typeof (MasterClientMessage)) &&
t.GetCustomAttribute<MasterClientMessageAttribute>() t.GetCustomAttribute<MasterClientMessageAttribute>()
.Name.Equals(commandName, StringComparison.OrdinalIgnoreCase))); .Name.Equals(commandName, StringComparison.OrdinalIgnoreCase)));

View File

@ -194,7 +194,7 @@ namespace NPSharp.NP
/// <param name="targetpath">Path where to save the file</param> /// <param name="targetpath">Path where to save the file</param>
public async void DownloadUserFileTo(string filename, string targetpath) public async void DownloadUserFileTo(string filename, string targetpath)
{ {
byte[] contents = await GetUserFile(filename); var contents = await GetUserFile(filename);
File.WriteAllBytes(targetpath, contents); File.WriteAllBytes(targetpath, contents);
} }
@ -231,7 +231,7 @@ namespace NPSharp.NP
/// <param name="targetpath">Path where to save the file</param> /// <param name="targetpath">Path where to save the file</param>
public async void DownloadPublisherFileTo(string filename, string targetpath) public async void DownloadPublisherFileTo(string filename, string targetpath)
{ {
byte[] contents = await GetPublisherFile(filename); var contents = await GetPublisherFile(filename);
File.WriteAllBytes(targetpath, contents); File.WriteAllBytes(targetpath, contents);
} }

View File

@ -53,7 +53,7 @@
<ItemGroup> <ItemGroup>
<Compile Include="Authentication\SessionAuthenticationClient.cs" /> <Compile Include="Authentication\SessionAuthenticationClient.cs" />
<Compile Include="Authentication\SessionAuthenticationResult.cs" /> <Compile Include="Authentication\SessionAuthenticationResult.cs" />
<Compile Include="Master\Client\MasterGetServersKeywords.cs" /> <Compile Include="Master\Data\MasterGetServersKeywords.cs" />
<Compile Include="Master\Client\MasterGetServersMessage.cs" /> <Compile Include="Master\Client\MasterGetServersMessage.cs" />
<Compile Include="Master\DedicatedServerEntry.cs" /> <Compile Include="Master\DedicatedServerEntry.cs" />
<Compile Include="Master\MasterClientMessage.cs" /> <Compile Include="Master\MasterClientMessage.cs" />

View File

@ -5,6 +5,7 @@ using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden // Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind. // die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("NPSharp client library")] [assembly: AssemblyTitle("NPSharp client library")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
@ -17,9 +18,11 @@ using System.Runtime.InteropServices;
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("eb49c20b-b649-42fa-bff4-f62aba36e0b0")] [assembly: Guid("eb49c20b-b649-42fa-bff4-f62aba36e0b0")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
@ -32,8 +35,10 @@ using System.Runtime.InteropServices;
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben: // übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0")] [assembly: AssemblyFileVersion("1.0")]
// Make internals visible to the server counterpart of this library // Make internals visible to the server counterpart of this library
[assembly: InternalsVisibleTo("npsharp_server")] [assembly: InternalsVisibleTo("npsharp_server")]

View File

@ -31,9 +31,17 @@ namespace NPSharp.RPC.Messages.Data
if (time.HasValue) if (time.HasValue)
Time = time.Value; Time = time.Value;
else else
Time = (uint)DateTime.Now.ToUniversalTime().ToBinary(); Time = (uint) DateTime.Now.ToUniversalTime().ToBinary();
} }
public uint Version { get; private set; }
public ulong ClientID { get; private set; }
public ulong ServerID { get; private set; }
public uint Time { get; private set; }
public byte[] Serialize() public byte[] Serialize()
{ {
using (var ms = new MemoryStream(sizeof (uint) + (sizeof (ulong)*2) + sizeof (uint))) using (var ms = new MemoryStream(sizeof (uint) + (sizeof (ulong)*2) + sizeof (uint)))
@ -49,13 +57,5 @@ namespace NPSharp.RPC.Messages.Data
} }
} }
} }
public uint Version { get; private set; }
public ulong ClientID { get; private set; }
public ulong ServerID { get; private set; }
public uint Time { get; private set; }
} }
} }

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="log4net" version="2.0.3" targetFramework="net45" /> <package id="log4net" version="2.0.3" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" /> <package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" />

View File

@ -24,7 +24,7 @@ namespace NPSharp.CommandLine.File
public Task Handle(IHttpContext context, Func<Task> next) public Task Handle(IHttpContext context, Func<Task> next)
{ {
string uri = context.Request.QueryString.Any() var uri = context.Request.QueryString.Any()
? null ? null
: string.Join("/", context.Request.Uri.OriginalString.Split('/').Skip(2)); : string.Join("/", context.Request.Uri.OriginalString.Split('/').Skip(2));
if (uri == null) if (uri == null)
@ -38,7 +38,7 @@ namespace NPSharp.CommandLine.File
} }
_log.InfoFormat("Requesting publisher file {0}", uri); _log.InfoFormat("Requesting publisher file {0}", uri);
Task<byte[]> task = _np.GetPublisherFile(uri); var task = _np.GetPublisherFile(uri);
try try
{ {
task.Wait(); task.Wait();

View File

@ -24,7 +24,7 @@ namespace NPSharp.CommandLine.File
public Task Handle(IHttpContext context, Func<Task> next) public Task Handle(IHttpContext context, Func<Task> next)
{ {
string uri = context.Request.QueryString.Any() var uri = context.Request.QueryString.Any()
? null ? null
: string.Join("/", context.Request.Uri.OriginalString.Split('/').Skip(2)); : string.Join("/", context.Request.Uri.OriginalString.Split('/').Skip(2));
if (uri == null) if (uri == null)
@ -38,7 +38,7 @@ namespace NPSharp.CommandLine.File
} }
_log.InfoFormat("Requesting user file {0}", uri); _log.InfoFormat("Requesting user file {0}", uri);
Task<byte[]> task = _np.GetUserFile(uri); var task = _np.GetUserFile(uri);
try try
{ {
task.Wait(); task.Wait();

View File

@ -14,7 +14,6 @@ using uhttpsharp.Handlers;
using uhttpsharp.Headers; using uhttpsharp.Headers;
using uhttpsharp.Listeners; using uhttpsharp.Listeners;
using uhttpsharp.RequestProviders; using uhttpsharp.RequestProviders;
using HttpResponse = uhttpsharp.HttpResponse;
namespace NPSharp.CommandLine.File namespace NPSharp.CommandLine.File
{ {
@ -96,9 +95,9 @@ namespace NPSharp.CommandLine.File
Console.ReadKey(); Console.ReadKey();
} }
} }
private static void SetupLog4Net() private static void SetupLog4Net()
{ {
if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
{ {
var appender = new ConsoleAppender var appender = new ConsoleAppender
@ -110,7 +109,8 @@ namespace NPSharp.CommandLine.File
#endif #endif
Layout = new PatternLayout("<%d{HH:mm:ss}> [%logger:%thread] %level: %message%newline"), Layout = new PatternLayout("<%d{HH:mm:ss}> [%logger:%thread] %level: %message%newline"),
}; };
BasicConfigurator.Configure(new IAppender[] { appender, new DebugAppender { Layout = appender.Layout, Threshold = Level.All } }); BasicConfigurator.Configure(new IAppender[]
{appender, new DebugAppender {Layout = appender.Layout, Threshold = Level.All}});
} }
else else
{ {
@ -150,10 +150,9 @@ namespace NPSharp.CommandLine.File
BackColor = ColoredConsoleAppender.Colors.Red BackColor = ColoredConsoleAppender.Colors.Red
}); });
appender.ActivateOptions(); appender.ActivateOptions();
BasicConfigurator.Configure(new IAppender[] { appender, new DebugAppender { Layout = appender.Layout, Threshold = Level.All } }); BasicConfigurator.Configure(new IAppender[]
{appender, new DebugAppender {Layout = appender.Layout, Threshold = Level.All}});
} }
} }
} }
} }

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="log4net" version="2.0.3" targetFramework="net45" /> <package id="log4net" version="2.0.3" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" /> <package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" />

View File

@ -3,29 +3,27 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using log4net; using log4net;
using NPSharp.Master.Messages; using NPSharp.Master.Messages;
using NPSharp.Master.Messages.Client; using NPSharp.Master.Messages.Client;
using NPSharp.NP;
namespace NPSharp.Master namespace NPSharp.Master
{ {
public class MasterServer public class MasterServer
{ {
// TODO: !! Avoid socket fail if stopping then restarting // TODO: !! Avoid socket fail if stopping then restarting
private readonly Socket _socket4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private readonly Socket _socket6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
private readonly ILog _log;
private readonly ushort _port;
private readonly List<KeyValuePair<Type, Action<MasterClientMessage>>> _callbacks = private readonly List<KeyValuePair<Type, Action<MasterClientMessage>>> _callbacks =
new List<KeyValuePair<Type, Action<MasterClientMessage>>>(); new List<KeyValuePair<Type, Action<MasterClientMessage>>>();
private readonly ILog _log;
private readonly ushort _port;
// TODO: Use the same kind of interfaces as in NP server to handle server addition and deletion // TODO: Use the same kind of interfaces as in NP server to handle server addition and deletion
private readonly List<DedicatedServerEntry> _registeredServers = new List<DedicatedServerEntry>(); private readonly List<DedicatedServerEntry> _registeredServers = new List<DedicatedServerEntry>();
private readonly Socket _socket4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private readonly Socket _socket6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
public MasterServer(ushort port = 20810) public MasterServer(ushort port = 20810)
{ {
@ -33,18 +31,15 @@ namespace NPSharp.Master
_log = LogManager.GetLogger("MasterServer"); _log = LogManager.GetLogger("MasterServer");
// Internal callbacks // Internal callbacks
AddCallback<MasterGetServersMessage>(messages => AddCallback<MasterGetServersMessage>(messages => { });
{
});
} }
internal void AddCallback<T>(Action<T> callback) where T : MasterClientMessage internal void AddCallback<T>(Action<T> callback) where T : MasterClientMessage
{ {
_callbacks.Add( _callbacks.Add(
new KeyValuePair<Type, Action<MasterClientMessage>>( new KeyValuePair<Type, Action<MasterClientMessage>>(
typeof(T), typeof (T),
msg => callback.Invoke((T)msg))); msg => callback.Invoke((T) msg)));
} }
/// <summary> /// <summary>
@ -86,7 +81,7 @@ namespace NPSharp.Master
while (true) while (true)
{ {
var buffer = new byte[1400]; var buffer = new byte[1400];
var clientEndPoint = (EndPoint)new IPEndPoint(IPAddress.IPv6Any, 0); var clientEndPoint = (EndPoint) new IPEndPoint(IPAddress.IPv6Any, 0);
var recvLength = _socket6.ReceiveFrom(buffer, ref clientEndPoint); var recvLength = _socket6.ReceiveFrom(buffer, ref clientEndPoint);
if (recvLength <= buffer.Length) if (recvLength <= buffer.Length)
mergedBuffer.AddRange(buffer); mergedBuffer.AddRange(buffer);
@ -118,6 +113,5 @@ namespace NPSharp.Master
_log.DebugFormat("Not handling client {0} anymore", ep); _log.DebugFormat("Not handling client {0} anymore", ep);
} }
} }
} }

View File

@ -34,10 +34,10 @@ namespace NPSharp.Master.Messages
internal static MasterServerMessage Deserialize(byte[] buffer) internal static MasterServerMessage Deserialize(byte[] buffer)
{ {
var header = buffer.Take(4).ToArray(); var header = buffer.Take(4).ToArray();
var command = Encoding.ASCII.GetString(buffer, 4, buffer.Length - 4).Trim(); var command = Encoding.ASCII.GetString(buffer, 4, buffer.Length - 4).Trim();
var commandSplit = command.Split(new[] { '\t', '\r', '\n', '\0', ' ' }, // TODO: Response consists of multipart messages separated by \ instead of <space>?? Try to be stay as close to client messages as possible. var commandSplit = command.Split(new[] {'\t', '\r', '\n', '\0', ' '},
// TODO: Response consists of multipart messages separated by \ instead of <space>?? Try to be stay as close to client messages as possible.
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
var commandName = commandSplit[0]; var commandName = commandSplit[0];
@ -45,11 +45,11 @@ namespace NPSharp.Master.Messages
// Search for a message class which fits to the commandName // Search for a message class which fits to the commandName
var message = var message =
(MasterServerMessage)Activator.CreateInstance(Assembly.GetExecutingAssembly() (MasterServerMessage) Activator.CreateInstance(Assembly.GetExecutingAssembly()
.GetTypes() .GetTypes()
.Single( .Single(
t => t =>
t.IsSubclassOf(typeof(MasterServerMessage)) && t.IsSubclassOf(typeof (MasterServerMessage)) &&
t.GetCustomAttribute<MasterServerMessageAttribute>() t.GetCustomAttribute<MasterServerMessageAttribute>()
.Name.Equals(commandName, StringComparison.OrdinalIgnoreCase))); .Name.Equals(commandName, StringComparison.OrdinalIgnoreCase)));

View File

@ -37,7 +37,7 @@ namespace NPSharp.NP
_clients = new List<NPServerClient>(); _clients = new List<NPServerClient>();
#if MONO_INCOMPATIBLE #if MONO_INCOMPATIBLE
// Mono can't compile this since the constructor is proprietary to Windows' .NET library // Mono can't compile this since the constructor is proprietary to Windows' .NET library
_socket = new Socket(SocketType.Stream, ProtocolType.IP); _socket = new Socket(SocketType.Stream, ProtocolType.IP);
// Mono can't compile this either since the IPv6Only socket option is completely missing. // Mono can't compile this either since the IPv6Only socket option is completely missing.
@ -168,7 +168,7 @@ namespace NPSharp.NP
_log.Debug("Async accept (IPv6) client start"); _log.Debug("Async accept (IPv6) client start");
allDone.Set(); allDone.Set();
var serverSocket = (Socket)ar.AsyncState; var serverSocket = (Socket) ar.AsyncState;
var clientSocket = serverSocket.EndAccept(ar); var clientSocket = serverSocket.EndAccept(ar);
var npsc = new NPServerClient(this, new RPCServerStream(clientSocket)); var npsc = new NPServerClient(this, new RPCServerStream(clientSocket));

View File

@ -4,6 +4,7 @@ using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden // Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind. // die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("NPSharp server library")] [assembly: AssemblyTitle("NPSharp server library")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<runtime> <runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">