83 lines
2.4 KiB
C#
83 lines
2.4 KiB
C#
using EonaCat.Json;
|
|
using EonaCat.Network;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace EonaCat.BlockChain
|
|
{
|
|
public class P2PClient
|
|
{
|
|
private readonly IDictionary<string, WSClient> wsDict = new Dictionary<string, WSClient>();
|
|
|
|
public void Connect(string url)
|
|
{
|
|
if (!wsDict.ContainsKey(url))
|
|
{
|
|
WSClient webSocket = new WSClient(url);
|
|
webSocket.OnMessageReceived += (sender, e) =>
|
|
{
|
|
if (e.Data == "Hi Client")
|
|
{
|
|
Console.WriteLine(e.Data);
|
|
}
|
|
else
|
|
{
|
|
var newChain = JsonHelper.ToObject<BlockChain>(e.Data);
|
|
if (!newChain.IsValid() || newChain.Chain.Count <= ClientServerExample.BlockChain.Chain.Count)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var newTransactions = new List<Transaction>();
|
|
newTransactions.AddRange(newChain.PendingTransactions);
|
|
newTransactions.AddRange(ClientServerExample.BlockChain.PendingTransactions);
|
|
|
|
newChain.PendingTransactions = newTransactions;
|
|
ClientServerExample.BlockChain = newChain;
|
|
}
|
|
};
|
|
webSocket.Connect();
|
|
webSocket.Send("Hi Server");
|
|
webSocket.Send(JsonHelper.ToJson(ClientServerExample.BlockChain));
|
|
wsDict.Add(url, webSocket);
|
|
}
|
|
}
|
|
|
|
public void Send(string url, string data)
|
|
{
|
|
foreach (var item in wsDict)
|
|
{
|
|
if (item.Key == url)
|
|
{
|
|
item.Value.Send(data);
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Broadcast(string data)
|
|
{
|
|
foreach (var item in wsDict)
|
|
{
|
|
item.Value.Send(data);
|
|
}
|
|
}
|
|
|
|
public IList<string> GetServers()
|
|
{
|
|
IList<string> servers = new List<string>();
|
|
foreach (var item in wsDict)
|
|
{
|
|
servers.Add(item.Key);
|
|
}
|
|
return servers;
|
|
}
|
|
|
|
public void Close()
|
|
{
|
|
foreach (var item in wsDict)
|
|
{
|
|
item.Value.Close();
|
|
}
|
|
}
|
|
}
|
|
} |