-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProgram.cs
More file actions
282 lines (242 loc) · 8.64 KB
/
Copy pathProgram.cs
File metadata and controls
282 lines (242 loc) · 8.64 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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using Expresharp;
using Expresharp.Fleck;
namespace CustomHttpServer
{
/// <summary>
/// Instead of <see cref="System.Net.HttpListener"/>, you may want to
/// customize your own HTTP server. This is quite simple with Expresharp.
/// Just wrap your requests/responses and push them into an Expresharp app
/// whenever you like.
///
/// In this example, we build an Expresharp app on an HTTP listener from
/// a 3rd-party package: websocket-sharp.
/// This package allows normal HTTP requests and websockets running together,
/// however kind of buggy (no offence, my Firefox said that).
/// Another package, Fleck, works fine with websockets, but gives up
/// usual HTTP requests.
///
/// Here in Expresharp, we combine these two great packages together.
///
/// The <see cref="System.Net.HttpListener"/> accepts WebSocket only on
/// .NET 4.5+ and Windows 8+, where that would be a better option.
/// </summary>
class Program
{
static void Main(string[] args)
{
// prepare an Express app
var app = new Express();
// same as usual
app.Get("/", (req, res) => res.Send("Hello World!"));
// set up a echo WebSocket handler on path "/echo"
var echo = new WebSocketMiddleware();
app.Use("/echo", echo);
// configure events of incoming websocket
echo.OnConnection(ws =>
{
ws.OnOpen = () => Console.WriteLine("Opened: {0}:{1}", ws.ConnectionInfo.ClientIpAddress, ws.ConnectionInfo.ClientPort);
ws.OnClose = () => Console.WriteLine("Closed: {0}:{1}", ws.ConnectionInfo.ClientIpAddress, ws.ConnectionInfo.ClientPort);
ws.OnError = e => Console.WriteLine("Error: {0}", e);
ws.OnMessage = msg =>
{
Console.WriteLine("Received: {0}", msg);
ws.Send("Echo: " + msg);
};
});
// start a listener from WebSocketSharp
var server = new WebSocketSharp.Net.HttpListener();
server.Prefixes.Add("http://localhost:8080/");
server.Start();
Console.WriteLine("Example app listening at {0}.", server.Prefixes.First());
while (server.IsListening)
{
// get a incoming request
var ctx = server.GetContext();
// wrap request/response
var req = new HttpListenerRequestWrapper(ctx.Request);
var res = new HttpListenerResponseWrapper(ctx.Response);
// extra works are needed if this is a WebSocket request
if (req.IsWebSocketRequest())
{
var wsCtx = ctx.AcceptWebSocket(null);
req.WebSocketContext = wsCtx;
res.WebSocketContext = wsCtx;
}
// push req/res into the Express app, it will take good care of them
app.Handle(req, res, null);
}
}
}
/// <summary>
/// Wraps a <see cref="WebSocketSharp.Net.HttpListenerRequest"/> as an <see cref="IHttpRequest"/>.
/// </summary>
class HttpListenerRequestWrapper : IHttpRequest
{
readonly WebSocketSharp.Net.HttpListenerRequest _request;
readonly IDictionary<Object, Object> _params = new Dictionary<Object, Object>();
private Stream _stream;
public HttpListenerRequestWrapper(WebSocketSharp.Net.HttpListenerRequest request)
{
_request = request;
}
public WebSocketSharp.Net.WebSockets.HttpListenerWebSocketContext WebSocketContext
{
set
{
// sorry for the break in :(, but the original underlying stream
// would be needed for reading/writing of WebSocket connection
_stream = (Stream)value.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic)
.First(p => p.PropertyType.Equals(typeof(Stream))).GetValue(value, null);
}
}
public WebSocketSharp.Net.HttpListenerRequest Request
{
get { return _request; }
}
public Version Version
{
get { return _request.ProtocolVersion; }
}
public String HttpMethod
{
get { return _request.HttpMethod; }
}
public String RawUrl
{
get { return _request.RawUrl; }
}
public Uri Url
{
get { return _request.Url; }
}
public String RouteUrl { get; set; }
public String BaseUrl { get; set; }
public NameValueCollection Headers
{
get { return _request.Headers; }
}
public Stream InputStream
{
get { return _stream ?? _request.InputStream; }
}
public IPEndPoint RemoteEndPoint
{
get { return _request.RemoteEndPoint; }
}
public String UserHostName
{
get { return _request.UserHostName; }
}
public void Params(Object key, Object value)
{
_params[key] = value;
}
public Object Params(Object key)
{
Object ret;
return _params.TryGetValue(key, out ret) ? ret : null;
}
public T ParamsAs<T>(Object key, T def = default(T))
{
Object result = Params(key);
return result != null ? (T)result : def;
}
}
/// <summary>
/// Wraps a <see cref="WebSocketSharp.Net.HttpListenerResponse"/> as an <see cref="IHttpResponse"/>.
/// </summary>
class HttpListenerResponseWrapper : IHttpResponse
{
readonly WebSocketSharp.Net.HttpListenerResponse _response;
private Stream _stream;
public HttpListenerResponseWrapper(WebSocketSharp.Net.HttpListenerResponse response)
{
_response = response;
}
public WebSocketSharp.Net.WebSockets.HttpListenerWebSocketContext WebSocketContext
{
set
{
// sorry for the break in too :(, but the original underlying stream
// would be needed for reading/writing of WebSocket connection
_stream = (Stream)value.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic)
.First(p => p.PropertyType.Equals(typeof(Stream))).GetValue(value, null);
}
}
public Int32 StatusCode
{
get { return _response.StatusCode; }
set
{
ClearWebSocketContext();
_response.StatusCode = value;
}
}
public String StatusDescription
{
get { return _response.StatusDescription; }
set
{
ClearWebSocketContext();
_response.StatusDescription = value;
}
}
public Stream OutputStream
{
get { return _stream ?? _response.OutputStream; }
}
public IHttpResponse Status(Int32 status)
{
StatusCode = status;
return this;
}
public IHttpResponse SetHeader(String key, String val)
{
_response.Headers[key] = val;
return this;
}
public void Redirect(String url)
{
ClearWebSocketContext();
_response.Redirect(url);
}
public void Send(String body)
{
ClearWebSocketContext();
if (_response.ContentType == null)
_response.ContentType = "text/html";
using (StreamWriter w = new StreamWriter(_response.OutputStream))
{
w.Write(body);
}
}
public void End()
{
if (_response != null)
_response.Close();
if (_stream != null)
_stream.Close();
}
public void Dispose()
{
if (_response != null)
((IDisposable)_response).Dispose();
if (_stream != null)
_stream.Dispose();
}
/// <summary>
/// Clears context of WebSocket so that this response could act like a normal one.
/// </summary>
private void ClearWebSocketContext()
{
_stream = null;
}
}
}