Skip to content

Instantly share code, notes, and snippets.

@waf
Created October 19, 2015 03:24
Show Gist options
  • Save waf/d5998682bdd808e64eaa to your computer and use it in GitHub Desktop.
Save waf/d5998682bdd808e64eaa to your computer and use it in GitHub Desktop.
F# websocket work-in-progress
type WebSocketResponse =
| Close
| Message of msg : string
let rec readMessagePatternMatch (ws:WebSocket) : Async<WebSocketResponse> =
let buffer : byte array = Array.zeroCreate 1024
let utf8 = new UTF8Encoding()
async {
let! payload = ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None) |> Async.AwaitTask
return! match payload.MessageType with
| WebSocketMessageType.Binary -> async.Return (failwith "unsupported binary message")
| WebSocketMessageType.Close -> async.Return WebSocketResponse.Close
| WebSocketMessageType.Text ->
let content = utf8.GetString(buffer)
if payload.EndOfMessage then
async.Return (WebSocketResponse.Message(content))
else
async {
let! next = readMessage ws
return match next with
| WebSocketResponse.Message(nextmsg) -> WebSocketResponse.Message(content + nextmsg)
| other -> other
}
| _ -> failwith "unexpected enum value"
}
let rec readMessageIfElse (ws:WebSocket) : Async<WebSocketResponse> =
let buffer : byte array = Array.zeroCreate 1024
let utf8 = new UTF8Encoding()
async {
let! payload = ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None) |> Async.AwaitTask
if payload.MessageType = WebSocketMessageType.Binary then
return failwith "unsupported binary message"
else if payload.MessageType = WebSocketMessageType.Close then
return WebSocketResponse.Close
else // if payload.MessageType = WebSocketMessageType.Text then
let content = utf8.GetString(buffer)
if payload.EndOfMessage then
return WebSocketResponse.Message(content)
else
let! successor = readMessage ws
return match successor with
| WebSocketResponse.Message(msg) -> WebSocketResponse.Message(content + msg)
| other -> other
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment