Update C# example client/server application. Other minor tweaks.

This commit is contained in:
Joseph Henry
2021-01-14 22:21:06 -08:00
parent f463d6c69f
commit b907635779
2 changed files with 129 additions and 112 deletions

View File

@@ -39,7 +39,7 @@ namespace ZeroTier
static ZeroTierManagedEventCallback _managedCallback; static ZeroTierManagedEventCallback _managedCallback;
// Callback used internally to ferry events from the C++ layer // Callback used internally to ferry events from the C++ layer
static void myZeroTierEventCallback(IntPtr msgPtr) static void OnZeroTierEvent(IntPtr msgPtr)
{ {
// Marshal the callback message pointer to a structure that we can inspect // Marshal the callback message pointer to a structure that we can inspect
zts_callback_msg msg = zts_callback_msg msg =
@@ -224,7 +224,7 @@ namespace ZeroTier
if (_hasBeenFreed == true) { if (_hasBeenFreed == true) {
throw new ObjectDisposedException("ZeroTier Node has previously been freed. Restart application to create new instance."); throw new ObjectDisposedException("ZeroTier Node has previously been freed. Restart application to create new instance.");
} }
return zts_start(_configFilePath,myZeroTierEventCallback,_servicePort); return zts_start(_configFilePath,OnZeroTierEvent,_servicePort);
} }
/// <summary> /// <summary>

View File

@@ -16,11 +16,11 @@ public class ExampleApp {
*/ */
public void StartZeroTier(string configFilePath, ushort servicePort, ulong networkId) public void StartZeroTier(string configFilePath, ushort servicePort, ulong networkId)
{ {
node = new ZeroTier.Node(configFilePath, myZeroTierEventCallback, servicePort); node = new ZeroTier.Node(configFilePath, OnZeroTierEvent, servicePort);
node.Start(); // Network activity only begins after calling Start() 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 /* How you do this next part is up to you, but essentially we're waiting for the node
to signal to us (via a ZeroTierEvent) that it has access to the internet and is to signal to us (via a ZeroTier.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 able to talk to one of our root servers. As a convenience you can just periodically check
IsOnline() instead of looking for the event via the callback. */ IsOnline() instead of looking for the event via the callback. */
while (!node.IsOnline()) { Thread.Sleep(100); } while (!node.IsOnline()) { Thread.Sleep(100); }
@@ -31,7 +31,7 @@ public class ExampleApp {
or removed routes, etc. */ or removed routes, etc. */
node.Join(networkId); node.Join(networkId);
/* Note that ZeroTierSocket calls will fail if there are no routes available, for this /* Note that ZeroTier.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 reason we should wait to make those calls until the node has indicated to us that at
least one network has been joined successfully. */ least one network has been joined successfully. */
while (!node.HasRoutes()) { Thread.Sleep(100); } while (!node.HasRoutes()) { Thread.Sleep(100); }
@@ -49,13 +49,13 @@ public class ExampleApp {
* Your application should process event messages and return control as soon as possible. Blocking * Your application should process event messages and return control as soon as possible. Blocking
* or otherwise time-consuming operations are not reccomended here. * or otherwise time-consuming operations are not reccomended here.
*/ */
public void myZeroTierEventCallback(ZeroTier.Event e) public void OnZeroTierEvent(ZeroTier.Event e)
{ {
Console.WriteLine("Event.eventCode = {0} ({1})", e.EventCode, e.EventName); Console.WriteLine("Event.eventCode = {0} ({1})", e.EventCode, e.EventName);
if (e.EventCode == ZeroTier.Constants.EVENT_NODE_ONLINE) { if (e.EventCode == ZeroTier.Constants.EVENT_NODE_ONLINE) {
Console.WriteLine("Node is online"); Console.WriteLine("Node is online");
Console.WriteLine(" - Address (NodeId): " + node.NodeId); Console.WriteLine(" - Address (NodeId): " + node.NodeId.ToString("x16"));
} }
if (e.EventCode == ZeroTier.Constants.EVENT_NETWORK_OK) { if (e.EventCode == ZeroTier.Constants.EVENT_NETWORK_OK) {
@@ -66,19 +66,15 @@ public class ExampleApp {
/** /**
* Example server * Example server
*/ */
public void YourServer() { public void YourServer(IPEndPoint localEndPoint) {
string data = null; string data = null;
// Data buffer for incoming data. // Data buffer for incoming data.
byte[] bytes = new Byte[1024]; byte[] bytes = new Byte[1024];
string serverIP = "0.0.0.0";
int port = 8000;
IPAddress ipAddress = IPAddress.Parse(serverIP);
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
Console.WriteLine(localEndPoint.ToString()); Console.WriteLine(localEndPoint.ToString());
ZeroTier.Socket listener = new ZeroTier.Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp ); ZeroTier.Socket listener = new ZeroTier.Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Bind the socket to the local endpoint and // Bind the socket to the local endpoint and
// listen for incoming connections. // listen for incoming connections.
@@ -100,15 +96,14 @@ public class ExampleApp {
// An incoming connection needs to be processed. // An incoming connection needs to be processed.
while (true) { while (true) {
int bytesRec = handler.Receive(bytes); int bytesRec = handler.Receive(bytes);
Console.WriteLine("Bytes received: {0}", bytesRec);
data += Encoding.ASCII.GetString(bytes,0,bytesRec); data += Encoding.ASCII.GetString(bytes,0,bytesRec);
if (data.IndexOf("<EOF>") > -1) {
if (bytesRec > 0) {
Console.WriteLine( "Text received : {0}", data);
break; break;
} }
} }
// Show the data on the console.
Console.WriteLine( "Text received : {0}", data);
// Echo the data back to the client. // Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data); byte[] msg = Encoding.ASCII.GetBytes(data);
@@ -117,8 +112,9 @@ public class ExampleApp {
handler.Close(); handler.Close();
} }
} catch (Exception e) { } catch (ZeroTier.ZeroTierException e) {
Console.WriteLine(e.ToString()); Console.WriteLine(e);
Console.WriteLine("ServiveErrorCode={0} SocketErrorCode={1}", e.ServiceErrorCode, e.SocketErrorCode);
} }
Console.WriteLine("\nPress ENTER to continue..."); Console.WriteLine("\nPress ENTER to continue...");
@@ -128,28 +124,23 @@ public class ExampleApp {
/** /**
* Example client * Example client
*/ */
public void YourClient() { public void YourClient(IPEndPoint remoteServerEndPoint) {
// Data buffer for incoming data. // Data buffer for incoming data.
byte[] bytes = new byte[1024]; byte[] bytes = new byte[1024];
// Connect to a remote device. // Connect to a remote device.
try { try {
string serverIP = "10.244.180.7";
int port = 8000;
IPAddress ipAddress = IPAddress.Parse(serverIP);
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket. // Create a TCP/IP socket.
ZeroTier.Socket sender = new ZeroTier.Socket(ipAddress.AddressFamily, ZeroTier.Socket sender = new ZeroTier.Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp ); SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors. // Connect the socket to the remote endpoint. Catch any errors.
try { try {
Console.WriteLine("Socket connecting to {0}...", Console.WriteLine("Socket connecting to {0}...",
remoteEndPoint.ToString()); remoteServerEndPoint.ToString());
sender.Connect(remoteEndPoint); sender.Connect(remoteServerEndPoint);
Console.WriteLine("Socket connected to {0}", Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString()); sender.RemoteEndPoint.ToString());
@@ -173,10 +164,10 @@ public class ExampleApp {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString()); Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) { } catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString()); Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) { } catch (ZeroTier.ZeroTierException e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString()); Console.WriteLine(e);
Console.WriteLine("ServiveErrorCode={0} SocketErrorCode={1}", e.ServiceErrorCode, e.SocketErrorCode);
} }
} catch (Exception e) { } catch (Exception e) {
Console.WriteLine( e.ToString()); Console.WriteLine( e.ToString());
} }
@@ -185,17 +176,43 @@ public class ExampleApp {
public class example public class example
{ {
static void Main() 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(); ExampleApp exampleApp = new ExampleApp();
ulong networkId = 0x8216ab0a47c622a1; if (args[0].Equals("server"))
ushort servicePort = 9991; {
string configFilePath = "path"; 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);
}
exampleApp.StartZeroTier(configFilePath, servicePort, networkId); if (args[0].Equals("client"))
exampleApp.YourClient(); {
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(); exampleApp.StopZeroTier();
return 0;
} }
} }