-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketServerHandler.cs
More file actions
146 lines (117 loc) · 4.49 KB
/
Copy pathSocketServerHandler.cs
File metadata and controls
146 lines (117 loc) · 4.49 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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
using System.Net;
using System.Text;
using System.Net.WebSockets;
using Newtonsoft.Json;
namespace SimpleOcppServer;
public class SocketServerHandler
{
private int count = 0;
private MessageHandler _handler;
private Dictionary<string, WebSocketContext> _connections;
public SocketServerHandler(MessageHandler handler)
{
_connections = new Dictionary<string, WebSocketContext>();
_handler = handler;
}
public async void Start(string listenerPrefix)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add(listenerPrefix);
listener.Start();
Console.WriteLine("Listening...");
while (true)
{
HttpListenerContext listenerContext = await listener.GetContextAsync();
if (listenerContext.Request.IsWebSocketRequest)
{
ProcessRequest(listenerContext);
}
else
{
listenerContext.Response.StatusCode = 400;
listenerContext.Response.Close();
}
}
}
internal async Task Send(string chargepoint, string messageType, object content)
{
var msgId = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var msg = new object[]
{
2,
msgId.ToString(),
messageType,
content
};
string data = JsonConvert.SerializeObject(msg);
Console.WriteLine($"Sending: {data}");
WebSocketContext context = _connections[chargepoint];
byte[] bytes = Encoding.ASCII.GetBytes(data);
await context.WebSocket.SendAsync(new ArraySegment<byte>(bytes),
WebSocketMessageType.Text, true, CancellationToken.None);
}
private async void ProcessRequest(HttpListenerContext listenerContext)
{
WebSocketContext webSocketContext = null;
string chargepointId = string.Empty;
try
{
webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol: null);
chargepointId = webSocketContext.RequestUri.ToString().Split("/").Last();
Console.WriteLine($"{chargepointId}");
if (_connections.ContainsKey(chargepointId))
{
_connections[chargepointId] = webSocketContext;
}
else
{
_connections.Add(chargepointId, webSocketContext);
}
Console.WriteLine($"Total connections: " + _connections.Count);
Interlocked.Increment(ref count);
Console.WriteLine("Processed: {0}", count);
}
catch (Exception e)
{
listenerContext.Response.StatusCode = 500;
listenerContext.Response.Close();
Console.WriteLine("Exception: {0}", e);
return;
}
WebSocket webSocket = webSocketContext.WebSocket;
try
{
while (webSocket.State == WebSocketState.Open)
{
byte[] receiveBuffer = new byte[1024];
WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
else if (receiveResult.MessageType == WebSocketMessageType.Text)
{
string request = System.Text.Encoding.Default.GetString(receiveBuffer);
var responseData = await _handler.GetResponse(chargepointId, request);
byte[] bytes = Encoding.ASCII.GetBytes(responseData);
await webSocket.SendAsync(new ArraySegment<byte>(bytes, 0, bytes.Length),
WebSocketMessageType.Text, receiveResult.EndOfMessage, CancellationToken.None);
}
else
{
await webSocket.SendAsync(new ArraySegment<byte>(receiveBuffer, 0, receiveResult.Count), WebSocketMessageType.Binary, receiveResult.EndOfMessage, CancellationToken.None);
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e);
}
finally
{
// Clean up by disposing the WebSocket once it is closed/aborted.
if (webSocket != null)
webSocket.Dispose();
}
}
}