diff options
| author | Sarah Bradley <git@sarahduck.ca> | 2023-12-01 20:33:42 -0800 |
|---|---|---|
| committer | Sarah Bradley <git@sarahduck.ca> | 2023-12-01 20:33:42 -0800 |
| commit | 2793b94040a473538f01723d5ca5f53c4535e2af (patch) | |
| tree | cb30f0dae20bda6ef9d1c005325bfd9c986b3c8f /NetClient.cs | |
What I've got so far
Diffstat (limited to 'NetClient.cs')
| -rw-r--r-- | NetClient.cs | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/NetClient.cs b/NetClient.cs new file mode 100644 index 0000000..31ea258 --- /dev/null +++ b/NetClient.cs @@ -0,0 +1,78 @@ +using System.Buffers.Binary; +using System.Net.Sockets; +using System.Text; + +namespace OnekoOnline.Net; + +static class Client +{ + static readonly TcpClient Tcp = new(); + static readonly UdpClient Udp = new(); + + public static readonly string UserName = OnekoOnline.Config.GetValue("UserName", "Oneko"); + public static int Id {get; private set;} = 0; + public static bool Connected => Tcp.Connected && Id != 0; + + public static Dictionary<int, User> Users = []; + static readonly Dictionary<int, User> allUsers = []; + + public static async void Init(string ServerAddress, int port) + { + if (ServerAddress == "") return; + + await Task.WhenAny(Tcp.ConnectAsync(ServerAddress, port), Task.Delay(3000)); + + if (Tcp.Connected) + { + Console.WriteLine("Connected to Server!"); + Udp.Connect(ServerAddress, port); + + CancellationTokenSource tokenSource = new(); + tokenSource.CancelAfter(5000); + + //Send Username + Packet packet = new(PacketType.Username, Encoding.UTF8.GetBytes(UserName), Id); + await NetBase.SendReliableData(packet, Tcp.GetStream(), tokenSource.Token); + //Send Oneko + packet = new(PacketType.OnekoSpritesheet, Oneko.LocalOneko!.SpriteSheet.Serialize(), Id); + await NetBase.SendReliableData(packet, Tcp.GetStream(), tokenSource.Token); + //Get Id + Packet idPacket = await NetBase.GetReliableData(Tcp.GetStream()); + Id = BinaryPrimitives.ReadInt32LittleEndian(idPacket.Data); + Console.WriteLine($"My ID is {Id}! {Connected}"); + + while (Connected) + { + if (Tcp.Available > 0) { + packet = await NetBase.GetReliableData(Tcp.GetStream()); + if (packet.FromId == 0) continue; //From server, ill implement later + + if (!allUsers.ContainsKey(packet.FromId)) { + allUsers.Add(packet.FromId, new User(packet.FromId)); + } + User sentFrom = allUsers[packet.FromId]; + + if (packet.Type == PacketType.OnekoSpritesheet) { + sentFrom.SpriteSheet = packet.Data; + } else if (packet.Type == PacketType.Username) { + sentFrom.Username = Encoding.UTF8.GetString(packet.Data); + } + + if (sentFrom.ExchangedData && !Users.ContainsKey(sentFrom.Id)) Users.Add(sentFrom.Id, sentFrom); + } + + if (Udp.Available > 0) { + } + + await Task.Delay(10); + } + } + else + { + Console.WriteLine("Connection to server failed."); + } + + Tcp.Dispose(); + Udp.Dispose(); + } +}
\ No newline at end of file |
