Skip to content

Server Example

Jim Schaad edited this page Jul 6, 2017 · 1 revision

Create the Server

CoapServer server = CoapServer();

For this server we are going to support both DTLS and UDP using the default port numbers. The issues of dealing with the different security requirements is deferred to the resources themselves. As an alternative, one can create two different servers each of which has either either it's own resources - or the same resource can be added to both servers.

Setup the UDP endpoint. We will use the default configuration and the default port number. If this is the only end point, then it will be created by default.

server.AddEndPoint(new CoapEndPoint());

Setup the DTLS endpoint. Since the system does not support the use of Raw Public Keys, the key set mySignKeys is currently not used. When support appears, then they would be placed in that key set.

KeySet mySignKeys = null;
KeySet mySharedKeys = new KeySet();

Create a new OneKey object that represents a shared secret for a DTLS connect. Additionally, it sets a user data field that can be associated with privileged data for security enforcement.

OneKey key = new OneKey();
key.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
key.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(new byte[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }));
key.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("ACE_KID1")));
key.UserData = "Level1";
mySharedKeys.AddKey(key);

key = new OneKey();
key.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
key.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(new byte[] { 12, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }));
key.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("ACE_KID2")));
key.UserData = "Level2";
mySharedKeys.AddKey(key);

Now create the actual DTLS end point and add it to the server.

CoAPEndPoint ep = new DTLSEndPoint(mySignKeys, mySharedKeys, 5689);
server.AddEndPoint(ep);

Add resources

By default, all resources added to the server will be "added" to the /.well-known/core resource unless they are tagged as being invisible. This is actually done by a tree walk when the directory links need to be created using the DiscoveryResource.

Add three resources to the server. These resource implementations can be found in the example server project.

server.Add(new HelloWorldResource("hello"));
server.Add(new FibonacciResource("fibonacci"));
server.Add(new TimeResource("time"));

Sometimes one will want to add a new resource and provide a path to the node where it is to be placed. Starting in drop 1.1.6 you can do this easily as follows.

server.Add("/.well-known", new Authz_Token("token"));

Getting server running

Finally, one needs to start the server operating.

server.Start();

Clean server shut down.

When the server exists, it is good to clean things up with the following.

server.Stop();