-
-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathProgram.cs
119 lines (93 loc) · 3.34 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
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
//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
//#define HAS_WIFI
using nanoFramework.Runtime.Events;
using nanoFramework.Networking;
using System;
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
#if HAS_WIFI
using System.Device.Wifi;
#endif
namespace SecureClient
{
public class Program
{
#if HAS_WIFI
private static string MySsid = "ssid";
private static string MyPassword = "password";
#endif
public static void Main()
{
Debug.WriteLine("Waiting for network up and IP address...");
bool success;
CancellationTokenSource cs = new(60000);
#if HAS_WIFI
success = WifiNetworkHelper.Reconnect();
#else
success = NetworkHelper.SetupAndConnectNetwork(cs.Token);
#endif
if (!success)
{
Debug.WriteLine($"{DateTime.UtcNow} Can't get a proper IP address, error: {NetworkHelper.Status}.");
if (NetworkHelper.HelperException != null)
{
Debug.WriteLine($"ex: {NetworkHelper.HelperException}");
}
return;
}
else
{
Debug.WriteLine($"{DateTime.UtcNow} Network connected");
}
// get host entry for How's my SSL test site
IPHostEntry hostEntry = Dns.GetHostEntry("httpbin.org");
// need an IPEndPoint from that one above
IPEndPoint ep = new IPEndPoint(hostEntry.AddressList[0], 80);
Debug.WriteLine($"{DateTime.UtcNow} Opening socket...{hostEntry.AddressList[0]} ");
using (Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
try
{
Debug.WriteLine("Connecting...");
// connect socket
mySocket.Connect(ep);
byte[] buffer = Encoding.UTF8.GetBytes("GET / HTTP/1.0\r\n\r\n");
mySocket.Send(buffer);
Debug.WriteLine($"Wrote {buffer.Length} bytes");
// set up buffer to read data from socket
buffer = new byte[1024];
// trying to read from socket
int bytes = mySocket.Receive(buffer);
Debug.WriteLine($"Read {bytes} bytes");
if (bytes > 0)
{
// we have data!
// output as string
Debug.WriteLine(new String(Encoding.UTF8.GetChars(buffer)));
}
}
catch (SocketException ex)
{
Debug.WriteLine($"** Socket exception occurred: {ex.Message} error code {ex.ErrorCode}!**");
}
catch (Exception ex)
{
Debug.WriteLine($"** Exception occurred: {ex.Message}!**");
}
finally
{
Debug.WriteLine("Closing socket");
mySocket.Close();
}
}
Thread.Sleep(Timeout.Infinite);
}
}
}