Net.BITKit.Teleport/Program.cs

128 lines
2.8 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// See https://aka.ms/new-console-template for more information
using System.Diagnostics;
using System.Globalization;
using System.Text;
using BITKit;
using BITKit.Mod;
using BITKit.Net;
using MemoryPack;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Net.BITKit.Teleport;
await BITAppForNet.InitializeAsync("Net.BITKit.Teleport");
var isClient = Environment.GetCommandLineArgs().Contains("client", StringComparer.CurrentCultureIgnoreCase);
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(x =>
{
x.AddConsole();
Console.OutputEncoding=Encoding.UTF8;
});
serviceCollection.AddTransient<NetProviderService>();
serviceCollection.AddSingleton<ENetServer>();
serviceCollection.AddSingleton<ENetClient>();
if (isClient)
{
serviceCollection.AddSingleton<INetProvider>(x => x.GetRequiredService<ENetClient>());
serviceCollection.AddRemoteInterface<IMyRemoteInterface>();
}
else
{
serviceCollection.AddSingleton<INetProvider>(x => x.GetRequiredService<ENetServer>());
serviceCollection.AddSingleton<IMyRemoteInterface,MyRemoteInterface>();
}
var serviceProvider = serviceCollection.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
if (isClient)
{
var client = serviceProvider.GetRequiredService<ENetClient>();
Tick(client);
if (await client.Connect() is false)
{
throw new Exception("Failed to connect to server.");
}
var rpc = serviceProvider.GetRequiredService<IMyRemoteInterface>();
for (int i = 1; i <= 3; i++)
{
//rpc.Func(i.ToString());
logger.LogInformation("Rpc:\t" + await rpc.FuncAsync(i.ToString()));
}
logger.LogInformation("客户端链接完成按任意键开始Rpc测试");
var isPressed=false;
Console.CancelKeyPress += (sender, args) =>
{
isPressed = true;
args.Cancel = true; // Prevent the process from terminating
};
while (true)
{
if (isPressed)
{
using var stopWatcher = new StopWatcher(logger,"Rpc测试");
logger.LogInformation("Rpc:\t" + await rpc.FuncAsync(DateTime.Now.ToString(CultureInfo.InvariantCulture)));
isPressed = false;
}
await Task.Delay(100);
}
}
else
{
var server = serviceProvider.GetRequiredService<ENetServer>();
Tick(server);
server.StartServer();
var count = 0;
while (true)
{
await Task.Delay(1000);
foreach (var id in server.Connections.Keys)
{
server.SendMessageToClient(id,$"Tick:{++count} from server!");
}
}
}
while (true)
{
await Task.Delay(300);
}
async void Tick(INetProvider netProvider)
{
while (true)
{
netProvider.Tick();
await Task.Delay(30);
}
}