1 module neton.server.PeerServers;
2 
3 import core.thread;
4 import std.array;
5 import std.conv;
6 
7 import hunt.logging;
8 import hunt.raft;
9 import hunt.net;
10 
11 import neton.network.NodeClient;
12 
13 
14 class PeerServers
15 {
16     private NodeClient[ulong] _clients;
17 	private __gshared PeerServers _gserver;
18 	private ulong _ID;
19 
20 	static PeerServers instance()
21 	{
22 		if (_gserver is null)
23 			_gserver = new PeerServers();
24 		return _gserver;
25 	}
26 
27 	void setID(ulong id)
28 	{
29 		_ID = id;
30 	}
31 
32     bool addPeer(ulong ID, string data)
33 	{
34 		logWarning("beging do connect : ",data);
35 		// if (ID in _clients)
36 		// 	return false;
37 
38 		auto client = new NodeClient(this._ID, ID);
39 		string[] hostport = split(data, ":");
40 		client.connect(hostport[0], to!int(hostport[1]), (AsyncResult!Connection result) {
41 			if (result.failed())
42 			{
43 				logWarning("connect fail --> : ", data);
44 				new Thread(() {
45 					Thread.sleep(dur!"seconds"(1));
46 					addPeer(ID, data);
47 				}).start();
48 				return;
49 			}
50 			_clients[ID] = client;
51 			logInfo(this._ID, " client connected ", hostport[0], " ", hostport[1]);
52 			// return true;
53 		});
54 
55 		return true;
56 	}
57 
58 	bool delPeer(ulong ID)
59 	{
60 		if (ID !in _clients)
61 			return false;
62 
63 		logInfo(_ID, " client disconnect ", ID);
64 		_clients[ID].close();
65 		_clients.remove(ID);
66 
67 		return true;
68 	}
69 
70 	void send(Message[] msg)
71 	{
72 		foreach (m; msg)
73 			_clients[m.To].write(m);
74 	}
75 }