-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathProgram.cs
executable file
·93 lines (78 loc) · 2.86 KB
/
Program.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
using System;
using System.Net;
using System.Text;
using System.Threading;
using CoAPNet;
using CoAPNet.Options;
using CoAPNet.Udp;
using CoAPNet.Server;
using System.Threading.Tasks;
namespace CoAPDevices
{
class Program
{
static async Task Main(string[] args)
{
// Create a task that finishes when Ctrl+C is pressed
var taskCompletionSource = new TaskCompletionSource<bool>();
// Capture the Control + C event
Console.CancelKeyPress += (s, e) =>
{
Console.WriteLine("Exiting");
taskCompletionSource.SetResult(true);
// Prevent the Main task from being destroyed prematurely.
e.Cancel = true;
};
Console.WriteLine("Press <Ctrl>+C to exit");
// Create a resource handler.
var myHandler = new CoapResourceHandler();
// Register a /hello resource.
myHandler.Resources.Add(new HelloResource("/hello"));
// Create a new CoapServer using UDP as it's base transport
var myServer = new CoapServer(new CoapUdpTransportFactory());
try
{
// Listen to all ip address and subscribe to multicast requests.
await myServer.BindTo(new CoapUdpEndPoint(Coap.Port) { JoinMulticast = true });
// Start our server.
await myServer.StartAsync(myHandler, CancellationToken.None);
Console.WriteLine("Server Started!");
// Wait indefinitely until the application quits.
await taskCompletionSource.Task;
}
catch (Exception ex)
{
// Canceled tasks are expected, safe to ignore.
if (ex is TaskCanceledException)
return;
Console.WriteLine($"Exception caught: {ex}");
Console.WriteLine($"Press <Enter> to exit");
Console.Read();
}
finally
{
Console.WriteLine("Shutting Down Server");
await myServer.StopAsync(CancellationToken.None);
}
}
}
public class HelloResource : CoapResource
{
public HelloResource(string uri) : base(uri)
{
Metadata.InterfaceDescription.Add("read");
Metadata.ResourceTypes.Add("message");
Metadata.Title = "Hello World";
}
public override CoapMessage Get(CoapMessage request)
{
Console.WriteLine($"Got request: {request}");
return new CoapMessage
{
Code = CoapMessageCode.Content,
Options = { new ContentFormat(ContentFormatType.TextPlain) },
Payload = Encoding.UTF8.GetBytes("Hello World!")
};
}
}
}