-
Notifications
You must be signed in to change notification settings - Fork 1
/
CSMSSimulator.cs
84 lines (74 loc) · 2.67 KB
/
CSMSSimulator.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
using System;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using Newtonsoft.Json.Linq;
namespace ocpp;
public class CSMSSimulator
{
public CSMSSimulator(int port)
{
this.Start("http://localhost:"+port+"/");
}
private int count = 0;
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();
}
}
}
private async void ProcessRequest(HttpListenerContext listenerContext)
{
WebSocketContext webSocketContext = null;
try
{
webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol: "ocpp1.6");
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
{
byte[] receiveBuffer = new byte[65535];
while (webSocket.State == WebSocketState.Open)
{
WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
if (receiveResult.MessageType == WebSocketMessageType.Text)
{
string buf = Encoding.ASCII.GetString(receiveBuffer);
buf = buf.Replace('\0', ' ').Trim();
}
}
}
catch(Exception e)
{
Console.WriteLine("Exception: {0}", e);
}
finally
{
if (webSocket != null)
webSocket.Dispose();
}
}
}