Skip to content

Instantly share code, notes, and snippets.

@panesofglass
Created December 2, 2010 20:18
Show Gist options
  • Select an option

  • Save panesofglass/725979 to your computer and use it in GitHub Desktop.

Select an option

Save panesofglass/725979 to your computer and use it in GitHub Desktop.
An example of writing a chat server using OWIN and F# Agents. See http://tomasp.net/blog/education-and-agents-talks.aspx
let root = @"C:\demos\FSharp.Agents\Demo.ChatServer\"
let cts = new CancellationTokenSource()
Owin.Extensions.Application.Start
("http://localhost:8082/", (fun request -> async {
match request.Path with // Path is an extension on IRequest to retrieve the path without the query string.
| "/post" ->
// Send message to the chat room
let! body = request.AsyncReadBody() // Extension that asynchronously reads the request body.
room.SendMessage(body) // room is an instance wrapping a F# MailboxProcessor<_>
Owin.Extensions.Response.Reply("OK")
| "/chat" ->
// Get messages from the chat room (asynchronously!)
let! text = room.AsyncGetContent()
Owin.Extensions.Response.Reply(text)
| s ->
// Handle an ordinary file request
let file =
root + (if s = "/" then "chat.html" else s.ToLower())
if File.Exists(file) then
let typ = contentTypes.[Path.GetExtension(file)]
Owin.Extensions.Response.Reply(typ, File.ReadAllBytes(file))
else
Owin.Extensions.Response.Reply(sprintf "File not found: %s" file) }),
cts.Token)
cts.Cancel()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment