EonaCat.Network/EonaCat.Network/System/BlockChain/P2PServer.cs

51 lines
1.7 KiB
C#

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<P2PServer>("/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<BlockChain>(e.Data);
if (newChain.IsValid() && newChain.Chain.Count > ClientServerExample.BlockChain.Chain.Count)
{
List<Transaction> newTransactions = new List<Transaction>();
newTransactions.AddRange(newChain.PendingTransactions);
newTransactions.AddRange(ClientServerExample.BlockChain.PendingTransactions);
newChain.PendingTransactions = newTransactions;
ClientServerExample.BlockChain = newChain;
}
if (!_chainSynched)
{
Send(JsonHelper.ToJson(ClientServerExample.BlockChain));
_chainSynched = true;
}
}
}
}
}