using EonaCat.Json; using EonaCat.Network; using System; using System.Collections.Generic; namespace EonaCat.BlockChain { public class P2PServer : WSEndpoint { private bool _chainSynched; private WSServer _wss; public void Start(string webSocketAddress = null) { webSocketAddress ??= $"ws://127.0.0.1:{ClientServerExample.ServerPort}"; _wss = new WSServer(webSocketAddress); _wss.AddEndpoint("/BlockChain"); _wss.Start(); Console.WriteLine($"Started server at {webSocketAddress}"); } protected override void OnMessage(MessageEventArgs e) { if (e.Data == "Hi Server") { Console.WriteLine(e.Data); Send("Hi Client"); } else { BlockChain newChain = JsonHelper.ToObject(e.Data); if (newChain.IsValid() && newChain.Chain.Count > ClientServerExample.BlockChain.Chain.Count) { List newTransactions = new List(); newTransactions.AddRange(newChain.PendingTransactions); newTransactions.AddRange(ClientServerExample.BlockChain.PendingTransactions); newChain.PendingTransactions = newTransactions; ClientServerExample.BlockChain = newChain; } if (!_chainSynched) { Send(JsonHelper.ToJson(ClientServerExample.BlockChain)); _chainSynched = true; } } } } }