Initial Commit

This commit is contained in:
SnapixLP | Tim G.
2025-05-19 09:16:34 +02:00
commit c214be937c
39 changed files with 3710 additions and 0 deletions

352
DX86/.gitignore vendored Normal file
View File

@@ -0,0 +1,352 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
.vscode/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
/.dotnet
/.packages
/.tools/vswhere/2.5.2
/.tools/native/iltools
### OSX ###
.DS_Store
.AppleDouble
.LSOverride
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# Exceptions to the exclusions
!src/Microsoft.DotNet.Wpf/src/WpfGfx/codegen/mcg/main/*.rsp
!src/Microsoft.DotNet.Wpf/src/WpfGfx/tools/csp/**/*.rsp

384
DX86/DX86.cs Normal file
View File

@@ -0,0 +1,384 @@
using DX86.Modules;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace DX86
{
/// <summary>
/// Represents the type of server, either TCP or UDP.
/// </summary>
public enum ServerType
{
TCP,
UDP
}
/// <summary>
/// The main class for the DX86 server. This class manages the TCP and UDP server functionality, including accepting client connections, receiving messages, and handling client disconnections.
/// </summary>
public class DX86
{
private MessageSender ms;
private TcpListener tcpServer;
private UdpClient udpServer;
private List<TcpClient> tcpClients = new List<TcpClient>();
private readonly object clientListLock = new object();
private ServerType serverType;
public event Action<TcpClient> ClientConnected;
public event Action<TcpClient, string> MessageReceived;
public event Action<TcpClient> ClientDisconnected;
public event Action<UdpClient> UdpClientConnected;
public event Action<IPEndPoint, string> UdpMessageReceived;
public event Action<UdpClient> UdpClientDisconnected;
public DX86(MessageSender ms, ServerType type)
{
this.ms = ms;
this.serverType = type;
ms.Log("[DX86] DX86 initialized for " + type.ToString() + " server.");
}
public void StartServer(string ipAddress, int port)
{
if (serverType == ServerType.TCP)
{
tcpServer = new TcpListener(IPAddress.Parse(ipAddress), port);
tcpServer.Start();
ms.Log($"[DX86] TCP server started on {ipAddress}:{port}");
AcceptTcpClientsAsync();
}
else if (serverType == ServerType.UDP)
{
udpServer = new UdpClient(port);
ms.Log($"[DX86] UDP server started on {ipAddress}:{port}");
ReceiveUdpMessagesAsync();
}
}
private async Task ReceiveUdpMessagesAsync()
{
while (true)
{
try
{
var receivedResult = await udpServer.ReceiveAsync();
string message = Encoding.UTF8.GetString(receivedResult.Buffer);
//ms.Log($"[DX86] Received UDP message from {receivedResult.RemoteEndPoint}: {message}");
// Trigger the event
UdpMessageReceived?.Invoke(receivedResult.RemoteEndPoint, message);
}
catch (Exception ex)
{
ms.Error("[DX86] Error receiving UDP message: " + ex.Message);
// Optionally handle specific exceptions or rethrow
}
}
}
public void StopServer()
{
if (serverType == ServerType.TCP)
{
tcpServer.Stop();
lock (clientListLock)
{
foreach (var client in tcpClients)
{
client.Close();
}
tcpClients.Clear();
}
ms.Log("[DX86] TCP server stopped.");
}
else if (serverType == ServerType.UDP)
{
udpServer.Close();
ms.Log("[DX86] UDP server stopped.");
}
}
private async Task AcceptTcpClientsAsync()
{
while (true)
{
var client = await tcpServer.AcceptTcpClientAsync();
lock (clientListLock)
{
tcpClients.Add(client);
}
ClientConnected?.Invoke(client);
ms.Log("[DX86] Client connected.");
HandleTcpClientAsync(client);
}
}
private async Task HandleTcpClientAsync(TcpClient client)
{
var stream = client.GetStream();
byte[] buffer = new byte[1024];
int numBytesRead;
try
{
while ((numBytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
string receivedMessage = Encoding.UTF8.GetString(buffer, 0, numBytesRead);
MessageReceived?.Invoke(client, receivedMessage);
//ms.Log($"[DX86] Message from client: {receivedMessage}");
BroadcastMessage(receivedMessage, client);
}
}
catch (Exception ex)
{
ms.Error("[DX86] Error handling client: " + ex.Message);
}
finally
{
lock (clientListLock)
{
tcpClients.Remove(client);
}
client.Close();
ClientDisconnected?.Invoke(client);
ms.Log("[DX86] Client disconnected.");
}
}
public async Task SendMessageAsync(TcpClient client, string message)
{
try
{
var stream = client.GetStream();
var buffer = Encoding.UTF8.GetBytes(message);
stream.WriteAsync(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
ms.Error($"[DX86] DX86 Failed to send message to {client.Client.RemoteEndPoint}: {ex.Message}");
}
}
public async Task SendUdpMessageAsync(string message, string ipAddress, int port)
{
try
{
var udpClient = new UdpClient();
var buffer = Encoding.UTF8.GetBytes(message);
await udpClient.SendAsync(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(ipAddress), port));
udpClient.Close();
ms.Log($"[DX86] Sent UDP message to {ipAddress}:{port}");
}
catch (Exception ex)
{
ms.Error("[DX86] Error sending UDP message: " + ex.Message);
}
}
public void BroadcastMessage(string message, TcpClient sender)
{
lock (clientListLock)
{
foreach (var client in tcpClients)
{
if (client != sender && client.Connected)
{
try
{
var buffer = Encoding.UTF8.GetBytes(message);
client.GetStream().WriteAsync(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
ms.Error($"[DX86] Failed to send message to {client.Client.RemoteEndPoint}: {ex.Message}");
}
}
}
}
}
public static string GetVersion()
{
return "0.243.554.3 - BETA";
}
}
}
/*
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace DX86
{
public class DX86
{
private MessageSender ms;
private TcpListener server;
private List<TcpClient> clients = new List<TcpClient>();
public event Action<TcpClient> ClientConnected;
public event Action<TcpClient, string> MessageReceived;
public event Action<TcpClient> ClientDisconnected;
public DX86(MessageSender ms)
{
this.ms = ms;
ms.Log("[DX86] DX86 initialized!");
}
public void StartServer(string ipAddress, int port)
{
server = new TcpListener(IPAddress.Parse(ipAddress), port);
server.Start();
ms.Log($"[DX86] DX86 started on {ipAddress}:{port}");
AcceptClientsAsync();
}
public void StopServer()
{
server.Stop(); // Stop the TcpListener.
foreach (var client in clients)
{
if (client.Connected)
{
client.Close(); // Disconnect each client.
}
}
clients.Clear(); // Clear the list of clients.
ms.Log("[DX86] DX86 stopped.");
}
private async Task AcceptClientsAsync()
{
while (true)
{
var client = await server.AcceptTcpClientAsync();
clients.Add(client);
ClientConnected?.Invoke(client);
ms.Log("[DX86] DX86 Client connected.");
HandleClientAsync(client);
}
}
private async Task HandleClientAsync(TcpClient client)
{
var stream = client.GetStream();
var buffer = new byte[1024];
try
{
while (true)
{
var byteCount = await stream.ReadAsync(buffer, 0, buffer.Length);
if (byteCount == 0) break;
var message = Encoding.UTF8.GetString(buffer, 0, byteCount);
MessageReceived?.Invoke(client, message);
BroadcastMessage(message, client);
}
}
catch (Exception ex)
{
ms.Error("[DX86] DX86: " + ex.Message);
}
finally
{
clients.Remove(client);
client.Close();
ClientDisconnected?.Invoke(client);
ms.Log("[DX86] DX86 Client disconnected.");
}
}
public async Task SendMessageAsync(TcpClient client, string message)
{
try
{
var stream = client.GetStream();
var buffer = Encoding.UTF8.GetBytes(message);
stream.WriteAsync(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
ms.Error($"[DX86] DX86 Failed to send message to {client.Client.RemoteEndPoint}: {ex.Message}");
}
}
private void BroadcastMessage(string message, TcpClient sender)
{
foreach (var client in clients)
{
if (client != sender)
{
try
{
var stream = client.GetStream();
var buffer = Encoding.UTF8.GetBytes(message);
stream.WriteAsync(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
ms.Error($"[DX86] DX86 Failed to send message to {client.Client.RemoteEndPoint}: {ex.Message}");
}
}
}
}
}
}
*/
/*
namespace DX86;
public class DX86
{
private MessageSender ms;
private List<Client?> clientList;
public DX86(MessageSender ms)
{
ms.Log("[DX86] Initializing DX86...");
this.ms = ms;
this.clientList = new List<Client?>();
ms.Log("[DX86] DX86 initialized!");
}
public void CreateClient()
{
clientList.Add(new Client());
}
public int GetClientCount()
{
return clientList.Count;
}
public Client? GetClient(int id)
{
try
{
return clientList[id];
}
catch (Exception e)
{
ms.Error("[DX86] Error getting client: " + e.Message);
return null;
}
}
}
*/

14
DX86/DX86.csproj Normal file
View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Folder Include="Modules\" />
</ItemGroup>
</Project>

63
DX86/Modules/InputBox.cs Normal file
View File

@@ -0,0 +1,63 @@
namespace DX86.Modules;
public class InputBox
{
private MessageSender ms;
public InputBox(MessageSender ms)
{
this.ms = ms;
ms.Log("[InputBox] InputBox initialized.");
}
public string ShowAsync(string title, List<string> lines)
{
ms.SaveOnly(true);
Console.Clear();
string message = "";
List<int> longestLine = new List<int>();
int lineNumber = 0;
foreach (var line in lines)
{
longestLine.Add(line.Length);
lineNumber++;
}
longestLine.Add(title.Length + 4);
int minLength = 50;
int maxLength = longestLine.Max();
if (maxLength < minLength)
{
maxLength = minLength;
}
string titleBar = new string('-', maxLength);
Console.WriteLine("+ {0} +", titleBar);
Console.WriteLine("| » {0}{1} |", title, new string(' ', (maxLength - title.Length) - 4));
Console.WriteLine("+ {0} +", titleBar);
for (int i = 0; i < lines.Count; i++)
{
Console.WriteLine("| {0}{1} |", lines[i], new string(' ', maxLength - longestLine[i]));
}
Console.WriteLine("+ {0} +", titleBar);
Console.WriteLine("| {0} |", new string(' ', maxLength));
Console.WriteLine("+ {0} +", titleBar);
Console.SetCursorPosition(2, 4+lines.Count);
string output = Console.ReadLine();
ms.SaveOnly(false);
ms.SendHistory();
return output;
}
}

View File

@@ -0,0 +1,158 @@
namespace DX86.Modules;
/*
* Copyright 2024 SnapixLP
*/
public class ItemSelector
{
private MessageSender ms;
public ItemSelector(MessageSender ms)
{
this.ms = ms;
ms.Log("[ItemSelector] ItemSelector initialized");
}
private string listTitle = "";
public void SetTitle(string title)
{
listTitle = title;
}
public string SelectItemFromList(string[] items)
{
bool noerror = true;
while (noerror)
{
try
{
Console.Clear();
ms.SaveOnly(true);
int cursorPosition = 1;
int listPosition = 1;
bool running = true;
while (running)
{
GenerateList(listTitle, items, cursorPosition, listPosition);
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
switch (keyInfo.Key)
{
case ConsoleKey.UpArrow:
cursorPosition -= 1;
break;
case ConsoleKey.DownArrow:
cursorPosition += 1;
break;
case ConsoleKey.W:
listPosition -= 1;
break;
case ConsoleKey.S:
listPosition += 1;
break;
case ConsoleKey.Enter:
running = false;
break;
case ConsoleKey.F1:
MessageBox mbox = new MessageBox(ms);
mbox.ShowAsync("Help", [
"Use the Arrow keys to select the items from the list.",
"Press enter to select the items from the list.",
"Press F1 to see this message.",
]);
break;
}
if (cursorPosition > items.Length)
{
cursorPosition = 1;
listPosition = 1;
}
if (cursorPosition < 1)
{
cursorPosition = items.Length;
listPosition = items.Length - 4;
}
if (listPosition > 1 && cursorPosition - listPosition == 0)
{
listPosition -= 1;
}
if (listPosition < items.Length - 4 && cursorPosition - listPosition == 4)
{
listPosition += 1;
}
Console.Clear();
}
ms.SaveOnly(false);
Console.Clear();
ms.SendHistory();
noerror = false;
return items[cursorPosition - 1];
}
catch (Exception e)
{
MessageBox messageBox = new MessageBox(ms);
ms.Error("[ItemSelector] [SelectItemFromList()] An Error Occured");
ms.Error(e.Message);
messageBox.ShowAsync("An error Occured | ItemSelector.cs at SelectItemFromList()", [e.Message, "", "Please try again..."]);
}
}
return "";
}
public static void GenerateList(string title, string[] items, int cursorPostion, int listPosition)
{
//Console.WriteLine($"{cursorPostion}, {listPosition}, {items.Length}, {cursorPostion - listPosition}, {listPosition < items.Length - 4}");;
string outMessage = "";
string headBar = "";
for (int i = 1; i <= title.Length; i++)
headBar += "=";
string titleSpace = "";
if (headBar.Length - (items[cursorPostion - 1].Length + 14) < 0)
{
// make int from negative to positive
int adjustedLength = Math.Abs(headBar.Length - (items[cursorPostion - 1].Length + 14));
for (int i = 1; i <= adjustedLength; i++)
{
headBar += "=";
titleSpace += " ";
}
}
string spaces = "";
for (int i = 1; i <= headBar.Length - (items[cursorPostion - 1].Length + 14); i++)
spaces += " ";
outMessage += $"[ {headBar} ]\n";
outMessage += ($"[ {title}{titleSpace} ]\n");
outMessage += ($"[ Current Item: {items[cursorPostion-1]} [{cursorPostion}/{items.Length}]{spaces} ]\n");
outMessage += ($"[ Press \"F1\" for help ]\n");
outMessage += "\n";
Console.WriteLine(outMessage);
int b = listPosition - 2;
for (int i = listPosition - 1; i < items.Length && i <= b + 5; i++)
{
if(i == cursorPostion - 1)
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("[" + listPosition + "] " + items[i]);
Console.ResetColor();
listPosition++;
}
else
{
Console.WriteLine("[" + listPosition + "] " + items[i]);
listPosition++;
}
}
}
}

View File

@@ -0,0 +1,55 @@
namespace DX86.Modules;
/*
* Copyright 2024 SnapixLP
*/
public class MessageBox
{
private MessageSender ms;
public MessageBox(MessageSender ms)
{
this.ms = ms;
ms.Log("[MessageBox] MessageBox initialized");
}
public async Task<string> ShowAsync(string title, List<string> lines)
{
ms.SaveOnly(true);
Console.Clear();
string message = "";
List<int> longestLine = new List<int>();
int lineNumber = 0;
foreach (var line in lines)
{
longestLine.Add(line.Length);
lineNumber++;
}
longestLine.Add(title.Length + 4);
int maxLength = longestLine.Max();
string titleBar = new string('-', maxLength);
Console.WriteLine("+ {0} +", titleBar);
Console.WriteLine("| » {0}{1} |", title, new string(' ', (maxLength - title.Length) - 4));
Console.WriteLine("+ {0} +", titleBar);
for (int i = 0; i < lines.Count; i++)
{
Console.WriteLine("| {0}{1} |", lines[i], new string(' ', maxLength - longestLine[i]));
}
Console.WriteLine("+ {0} +", titleBar);
Console.Write(" »» Press any key to continue...");
Console.ReadKey();
ms.SaveOnly(false);
ms.SendHistory();
return "OK";
}
}

View File

@@ -0,0 +1,95 @@
namespace DX86.Modules;
/*
* Copyright 2024 SnapixLP
*/
public class MessageSender
{
private string[] messageHistory = {};
private bool saveOnly = false;
private string logfile;
public MessageSender(string logfile)
{
this.logfile = logfile;
if (!File.Exists(logfile))
{
File.Create(logfile).Close();
Log("[MessageSender] Log file created.");
}
Log("[MessageSender] Starting Logoutput to " + logfile);
Log("[MessageSender] MessageSender initialized.");
}
private async Task WriteToFileAsync(string message)
{
try
{
using (StreamWriter writer = new StreamWriter(logfile, true))
{
await writer.WriteLineAsync(message);
}
}
catch (Exception ex)
{
Error($"Failed to write to log file: {ex.Message}");
}
}
public async void Log(string message)
{
Console.ForegroundColor = ConsoleColor.Gray;
this.Send($"[{DateTime.Now}] [INFO ] {message}");
}
public async void Warn(string message)
{
Console.ForegroundColor = ConsoleColor.Yellow;
this.Send($"[{DateTime.Now}] [WARN ] {message}");
Console.ForegroundColor = ConsoleColor.Gray;
}
public async void Error(string message)
{
Console.ForegroundColor = ConsoleColor.Red;
this.Send($"[{DateTime.Now}] [ERROR] {message}");
Console.ForegroundColor = ConsoleColor.Gray;
}
private async void Send(string message)
{
WriteToFileAsync(message);
if (!saveOnly)
{
Console.WriteLine(message);
}
messageHistory = messageHistory.Concat(new[] { message }).ToArray();
if (messageHistory.Length > 50)
{
messageHistory = messageHistory.Skip(1).ToArray();
}
}
public async void SendHistory()
{
int i = 0;
foreach (var s in messageHistory)
{
if (s.Contains("[INFO ]"))
Console.ForegroundColor = ConsoleColor.Gray;
if (s.Contains("[WARN ]"))
Console.ForegroundColor = ConsoleColor.Yellow;
if (s.Contains("[ERROR]"))
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"{s}");
Console.ForegroundColor = ConsoleColor.Gray;
}
}
public void SaveOnly(bool newValue)
{
saveOnly = newValue;
}
}

11
DX86/Program.cs Normal file
View File

@@ -0,0 +1,11 @@
namespace DX86;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to DX86!");
Console.WriteLine("Please do not run this program as itself.");
Console.WriteLine("DX86 is only a dependency for other programs.");
}
}

107
DX86/TcpServer.cs Normal file
View File

@@ -0,0 +1,107 @@
using System.Net;
using System.Net.Sockets;
using DX86.Modules;
namespace DX86;
using System.Net.Sockets;
public abstract class TcpServer
{
private string address;
private int port;
protected MessageSender ms;
private DX86 dx86;
public List<string> optionsList;
public TcpServer(string address, int port, MessageSender ms)
{
ms.Log("[DX86] Setting up server.");
this.address = address;
this.port = port;
this.ms = ms;
optionsList = new List<string>();
this.dx86 = new DX86(ms, ServerType.TCP);
optionsList.Add("cancel");
ms.Log("[DX86] Server Setup Complete.");
_ = RunServer();
}
private async Task RunServer()
{
ms.Log("[DX86] Starting server.");
// Subscribe to events
dx86.ClientConnected += ClientConnectEvent;
dx86.MessageReceived += MessageReceivedEvent;
dx86.ClientDisconnected += ClientDisconnectEvent;
// Start the server
dx86.StartServer(address, port);
ms.Log("[DX86] Server started.");
// Keep the server running indefinitely
await Task.Delay(Timeout.Infinite);
}
public void StopServer()
{
ms.Log("[DX86] Got Signal to Stop Server.");
dx86.StopServer();
ms.Log("[DX86] Server stopped.");
}
public string GetAddress()
{
return address;
}
public int GetPort()
{
return port;
}
public void SendMessageAsync(TcpClient client, string message)
{
dx86.SendMessageAsync(client, message);
}
public void BroadcastMessageAsync(TcpClient sender, string message)
{
dx86.BroadcastMessage(message, sender);
}
public IPEndPoint GetClientEndPoint(TcpClient client)
{
if (client == null)
{
return null;
}
if (!client.Connected)
{
return null;
}
// Get the remote endpoint, cast it to IPEndPoint
IPEndPoint remoteEndPoint = client.Client.RemoteEndPoint as IPEndPoint;
if (remoteEndPoint != null)
{
// Return the IP address and port
return remoteEndPoint;
}
return null;
}
public abstract string ToggleOption(string option, string value);
public abstract List<List<string>> ConfigureOptions(string option);
// Define your event handlers
protected abstract void ClientConnectEvent(TcpClient client);
protected abstract void MessageReceivedEvent(TcpClient client, string message);
protected abstract void ClientDisconnectEvent(TcpClient client);
}

71
DX86/UdpServer.cs Normal file
View File

@@ -0,0 +1,71 @@
using System.Net.Sockets;
using DX86.Modules;
namespace DX86;
using System.Net.Sockets;
public abstract class UdpServer
{
private string address;
private int port;
protected MessageSender ms;
private DX86 dx86;
public UdpServer(string address, int port, MessageSender ms)
{
ms.Log("[DX86] Setting up server.");
this.address = address;
this.port = port;
this.ms = ms;
this.dx86 = new DX86(ms, ServerType.UDP);
ms.Log("[DX86] Server Setup Complete.");
_ = RunServer();
}
private async Task RunServer()
{
ms.Log("[DX86] Starting server.");
// Subscribe to events
dx86.ClientConnected += ClientConnectEvent;
dx86.MessageReceived += MessageReceivedEvent;
dx86.ClientDisconnected += ClientDisconnectEvent;
// Start the server
dx86.StartServer(address, port);
ms.Log("[DX86] Server started.");
// Keep the server running indefinitely
await Task.Delay(Timeout.Infinite);
}
public void StopServer()
{
ms.Log("[DX86] Got Signal to Stop Server.");
dx86.StopServer();
ms.Log("[DX86] Server stopped.");
}
public string GetAddress()
{
return address;
}
public int GetPort()
{
return port;
}
public void SendMessageAsync(TcpClient client, string message)
{
dx86.SendMessageAsync(client, message);
}
// Define your event handlers
protected abstract void ClientConnectEvent(TcpClient client);
protected abstract void MessageReceivedEvent(TcpClient client, string message);
protected abstract void ClientDisconnectEvent(TcpClient client);
}