forked from gdamore/libzt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.cs
264 lines (224 loc) · 8.07 KB
/
example.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets; // For SocketType, etc
using System.Text; // For Encoding
/**
*
* Namespaces explained:
*
* ZeroTier.Core (API to control a ZeroTier Node)
* -> class ZeroTier.Core.Node
* -> class ZeroTier.Core.Event
*
* ZeroTier.Sockets (Socket API similar to System.Net.Sockets)
* -> class ZeroTier.Sockets.Socket
* -> class ZeroTier.Sockets.SocketException
*
* ZeroTier.Central (upcoming)
*
*/
using ZeroTier;
public class ExampleApp {
ZeroTier.Core.Node node;
/**
* Initialize and start ZeroTier
*/
public void StartZeroTier(string configFilePath, ushort servicePort, ulong networkId)
{
node = new ZeroTier.Core.Node(configFilePath, OnZeroTierEvent, servicePort);
node.Start(); // Network activity only begins after calling Start()
/* How you do this next part is up to you, but essentially we're waiting for the node
to signal to us via OnZeroTierEvent(ZeroTier.Core.Event) that it has access to the
internet and is able to talk to one of our root servers. As a convenience you can just
periodically check Node.IsOnline() instead of looking for the event via the callback. */
while (!node.IsOnline()) { Thread.Sleep(100); }
/* After the node comes online you may now join/leave networks. You will receive
notifications via the callback function regarding the status of your join request as well
as any subsequent network-related events such as the assignment of an IP address, added
or removed routes, etc. */
node.Join(networkId);
/* Note that ZeroTier.Sockets.Socket calls will fail if there are no routes available, for this
reason we should wait to make those calls until the node has indicated to us that at
least one network has been joined successfully. */
while (!node.HasRoutes()) { Thread.Sleep(100); }
}
/**
* Stop ZeroTier
*/
public void StopZeroTier()
{
node.Stop();
}
/**
* Your application should process event messages and return control as soon as possible. Blocking
* or otherwise time-consuming operations are not reccomended here.
*/
public void OnZeroTierEvent(ZeroTier.Core.Event e)
{
Console.WriteLine("Event.eventCode = {0} ({1})", e.EventCode, e.EventName);
if (e.EventCode == ZeroTier.Constants.EVENT_NODE_ONLINE) {
Console.WriteLine("Node is online");
Console.WriteLine(" - Address (NodeId): " + node.NodeId.ToString("x16"));
}
if (e.EventCode == ZeroTier.Constants.EVENT_NETWORK_OK) {
Console.WriteLine(" - Network ID: " + e.networkDetails.networkId.ToString("x16"));
}
}
/**
* Example server
*/
public void YourServer(IPEndPoint localEndPoint) {
string data = null;
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
Console.WriteLine(localEndPoint.ToString());
ZeroTier.Sockets.Socket listener = new ZeroTier.Sockets.Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Bind the socket to the local endpoint and
// listen for incoming connections.
try {
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true) {
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
bool nonblocking = true;
ZeroTier.Sockets.Socket handler;
if (nonblocking) { // Non-blocking style Accept() loop using Poll()
Console.WriteLine("Starting non-blocking Accept() loop...");
listener.Blocking = false;
// loop
int timeout = 100000; // microseconds (1 second)
while (true) {
Console.WriteLine("Polling... (for data or incoming connections)");
if (listener.Poll(timeout, SelectMode.SelectRead)) {
Console.WriteLine("Detected event (SelectRead). Accepting...");
handler = listener.Accept();
break;
}
//Thread.Sleep(5);
}
}
else { // Blocking style
Console.WriteLine("Starting blocking Accept() call...");
handler = listener.Accept();
}
data = null;
Console.WriteLine("Accepted connection from: " + handler.RemoteEndPoint.ToString());
// handler.ReceiveTimeout = 1000;
// An incoming connection needs to be processed.
while (true) {
int bytesRec = 0;
try {
Console.WriteLine("Receiving...");
bytesRec = handler.Receive(bytes);
}
catch (ZeroTier.Sockets.SocketException e)
{
Console.WriteLine("ServiveErrorCode={0} SocketErrorCode={1}", e.ServiceErrorCode, e.SocketErrorCode);
}
if (bytesRec > 0) {
Console.WriteLine("Bytes received: {0}", bytesRec);
data = Encoding.ASCII.GetString(bytes,0,bytesRec);
Console.WriteLine( "Text received : {0}", data);
//break;
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
}
else
{
System.GC.Collect();
Console.WriteLine("No data...");
}
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
} catch (ZeroTier.Sockets.SocketException e) {
Console.WriteLine(e);
Console.WriteLine("ServiveErrorCode={0} SocketErrorCode={1}", e.ServiceErrorCode, e.SocketErrorCode);
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
/**
* Example client
*/
public void YourClient(IPEndPoint remoteServerEndPoint) {
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Create a TCP/IP socket.
ZeroTier.Sockets.Socket sender = new ZeroTier.Sockets.Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors.
try {
Console.WriteLine("Socket connecting to {0}...",
remoteServerEndPoint.ToString());
sender.Connect(remoteServerEndPoint);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (ZeroTier.Sockets.SocketException e) {
Console.WriteLine(e);
Console.WriteLine("ServiveErrorCode={0} SocketErrorCode={1}", e.ServiceErrorCode, e.SocketErrorCode);
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}
}
public class example
{
static int Main(string[] args)
{
if (args.Length < 5 || args.Length > 6)
{
Console.WriteLine("\nPlease specify either client or server mode and required arguments:");
Console.WriteLine(" Usage: example server <config_path> <ztServicePort> <nwid> <serverPort>");
Console.WriteLine(" Usage: example client <config_path> <ztServicePort> <nwid> <remoteServerIp> <remoteServerPort>\n");
return 1;
}
string configFilePath = args[1];
ushort servicePort = (ushort)Int16.Parse(args[2]);
ulong networkId = (ulong)Int64.Parse(args[3], System.Globalization.NumberStyles.HexNumber);
ExampleApp exampleApp = new ExampleApp();
if (args[0].Equals("server"))
{
Console.WriteLine("Server mode...");
ushort serverPort = (ushort)Int16.Parse(args[4]);
exampleApp.StartZeroTier(configFilePath, servicePort, networkId);
IPAddress ipAddress = IPAddress.Parse("0.0.0.0");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, serverPort);
exampleApp.YourServer(localEndPoint);
}
if (args[0].Equals("client"))
{
Console.WriteLine("Client mode...");
string serverIP = args[4];
int port = Int16.Parse(args[5]);
IPAddress ipAddress = IPAddress.Parse(serverIP);
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, port);
exampleApp.StartZeroTier(configFilePath, servicePort, networkId);
exampleApp.YourClient(remoteEndPoint);
}
exampleApp.StopZeroTier();
return 0;
}
}