Skip to content

Instantly share code, notes, and snippets.

@conradz
Created September 10, 2012 21:25
Show Gist options
  • Save conradz/3693987 to your computer and use it in GitHub Desktop.
Save conradz/3693987 to your computer and use it in GitHub Desktop.
Use custom server for Fleck websockets
// In the HTTP handler method:
WebSocketConnection connection = null;
connection = new WebSocketConnection(
new SocketWrapper(response.Socket),
Accept,
b => MapRequest(request), // Creates the `WebSocketHttpRequest` from my `request` object
r => HandlerFactory.BuildHandler(
r,
s => connection.OnMessage(s),
() => connection.Close(),
(b) => connection.OnBinary(b)));
// Call the `CreateHandler` method with empty data
connection.GetType().GetMethod(
"CreateHandler",
BindingFlags.Default | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
.Invoke(connection, new object[] { Enumerable.Empty<byte>() });
connection.StartReceiving();
// Methods:
private WebSocketHttpRequest MapRequest(HttpRequest request)
{
// `request` is my custom object that contains the request data
var wsRequest = new WebSocketHttpRequest()
{
Body = request.Body == null ? "" : Encoding.UTF8.GetString(request.Body),
Bytes = request.Body,
Method = request.Method,
Path = request.Path,
Scheme = "ws"
};
// Headers are stored in a NameValueCollection
foreach (string key in request.Headers.AllKeys)
wsRequest.Headers[key] = request.Headers[key];
return wsRequest;
}
private void Accept(IWebSocketConnection socket)
{
// Dummy method
socket.OnMessage = m => Debug.WriteLine(m);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment