-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClient.cs
More file actions
70 lines (59 loc) · 2.83 KB
/
HttpClient.cs
File metadata and controls
70 lines (59 loc) · 2.83 KB
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
using System;
using Microsoft.SPOT;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
namespace netduino_p1_logging {
public static class HttpClient {
public static bool TryConnect(this Socket s, EndPoint ep, int timeout) {
bool connected = false;
new Thread(delegate {
try {
// s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Linger, new byte[] { 0, 0, 0, 0 });
s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, false);
s.SendTimeout = timeout;
s.ReceiveTimeout = timeout;
s.Connect(ep);
connected = true;
} catch { }
}).Start();
int checks = 10;
while (checks-- > 0 && connected == false) Thread.Sleep(100);
// if (connected == false) throw new Exception("Failed to connect");
return connected;
}
public static IPEndPoint GetIPEndPoint(string host, int port = 80) {
// look up host’s domain name to find IP address(es)
IPHostEntry hostEntry = Dns.GetHostEntry(host);
// extract a returned address
IPAddress hostAddress = hostEntry.AddressList[0];
IPEndPoint remoteEndPoint = new IPEndPoint(hostAddress, port);
return remoteEndPoint;
}
public static Socket Connect(IPEndPoint remoteEndPoint, int timeout) {
// connect!
Debug.Print("connect...");
var connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connection.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
connection.SendTimeout = timeout;
connection.ReceiveTimeout = timeout;
if (connection.TryConnect(remoteEndPoint, timeout))
return connection;
else
return null;
}
public static void SendRequest(Socket s, string host, string request, string content) {
byte[] contentBuffer = Encoding.UTF8.GetBytes(content);
const string CRLF = "\r\n";
var requestLine = request + CRLF;
var headers = requestLine + "Host: " + host + CRLF +
"Content-Type: application/json" + CRLF +
"Content-Length: " + contentBuffer.Length + CRLF + CRLF;
byte[] headersBuffer = Encoding.UTF8.GetBytes(headers);
s.Send(headersBuffer);
s.Send(contentBuffer);
}
}
}