5 people like it.

Start Suave server on first free port

This looks for the first available port and starts a Suave server on the port. The function is asynchronous and returns the port once the server is started.

 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: 
open Suave

/// Sample server that we want to host
let app = Successful.OK "Hello world!"

/// Start server on the first available port in the range 8000..10000
/// and return the port number once the server is started (asynchronously)
let startServer () =
  Async.FromContinuations(fun (cont, _, _) ->
    let startedEvent = Event<_>()
    startedEvent.Publish.Add(cont)
    async {
      // Try random ports until we find one that works
      let rnd = System.Random()
      while true do 
        let port = 8000 + rnd.Next(2000)
        let local = Suave.Http.HttpBinding.mkSimple HTTP "127.0.0.1" port
        let logger = Suave.Logging.Loggers.saneDefaultsFor Logging.LogLevel.Error
        let config = { defaultConfig with bindings = [local]; logger = logger }
        let started, start = startWebServerAsync config app
        // If it starts OK, we get TCP binding & report success via event
        async { let! running = started   
                startedEvent.Trigger(running) } |> Async.Start                    
        // Try starting the server and handle SocketException
        try do! start
        with :? System.Net.Sockets.SocketException -> () } 
    |> Async.Start )
namespace Suave
val app : WebPart

Full name: Script.app


 Sample server that we want to host
module Successful

from Suave
val OK : body:string -> WebPart

Full name: Suave.Successful.OK
val startServer : unit -> Async<Tcp.StartedData option []>

Full name: Script.startServer


 Start server on the first available port in the range 8000..10000
 and return the port number once the server is started (asynchronously)
Multiple items
type Async
static member AsBeginEnd : computation:('Arg -> Async<'T>) -> ('Arg * AsyncCallback * obj -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit)
static member AwaitEvent : event:IEvent<'Del,'T> * ?cancelAction:(unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate)
static member AwaitIAsyncResult : iar:IAsyncResult * ?millisecondsTimeout:int -> Async<bool>
static member AwaitTask : task:Task -> Async<unit>
static member AwaitTask : task:Task<'T> -> Async<'T>
static member AwaitWaitHandle : waitHandle:WaitHandle * ?millisecondsTimeout:int -> Async<bool>
static member CancelDefaultToken : unit -> unit
static member Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
static member FromBeginEnd : beginAction:(AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg:'Arg1 * beginAction:('Arg1 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * beginAction:('Arg1 * 'Arg2 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * arg3:'Arg3 * beginAction:('Arg1 * 'Arg2 * 'Arg3 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromContinuations : callback:(('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
static member Ignore : computation:Async<'T> -> Async<unit>
static member OnCancel : interruption:(unit -> unit) -> Async<IDisposable>
static member Parallel : computations:seq<Async<'T>> -> Async<'T []>
static member RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:CancellationToken -> 'T
static member Sleep : millisecondsDueTime:int -> Async<unit>
static member Start : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions * ?cancellationToken:CancellationToken -> Task<'T>
static member StartChild : computation:Async<'T> * ?millisecondsTimeout:int -> Async<Async<'T>>
static member StartChildAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions -> Async<Task<'T>>
static member StartImmediate : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartWithContinuations : computation:Async<'T> * continuation:('T -> unit) * exceptionContinuation:(exn -> unit) * cancellationContinuation:(OperationCanceledException -> unit) * ?cancellationToken:CancellationToken -> unit
static member SwitchToContext : syncContext:SynchronizationContext -> Async<unit>
static member SwitchToNewThread : unit -> Async<unit>
static member SwitchToThreadPool : unit -> Async<unit>
static member TryCancelled : computation:Async<'T> * compensation:(OperationCanceledException -> unit) -> Async<'T>
static member CancellationToken : Async<CancellationToken>
static member DefaultCancellationToken : CancellationToken

Full name: Microsoft.FSharp.Control.Async

--------------------
type Async<'T>

Full name: Microsoft.FSharp.Control.Async<_>
static member Async.FromContinuations : callback:(('T -> unit) * (exn -> unit) * (System.OperationCanceledException -> unit) -> unit) -> Async<'T>
val cont : (Tcp.StartedData option [] -> unit)
val startedEvent : Event<Tcp.StartedData option []>
Multiple items
module Event

from Microsoft.FSharp.Control

--------------------
type Event<'T> =
  new : unit -> Event<'T>
  member Trigger : arg:'T -> unit
  member Publish : IEvent<'T>

Full name: Microsoft.FSharp.Control.Event<_>

--------------------
type Event<'Delegate,'Args (requires delegate and 'Delegate :> Delegate)> =
  new : unit -> Event<'Delegate,'Args>
  member Trigger : sender:obj * args:'Args -> unit
  member Publish : IEvent<'Delegate,'Args>

Full name: Microsoft.FSharp.Control.Event<_,_>

--------------------
new : unit -> Event<'T>

--------------------
new : unit -> Event<'Delegate,'Args>
property Event.Publish: IEvent<Tcp.StartedData option []>
member System.IObservable.Add : callback:('T -> unit) -> unit
val async : AsyncBuilder

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async
val rnd : System.Random
namespace System
Multiple items
type Random =
  new : unit -> Random + 1 overload
  member Next : unit -> int + 2 overloads
  member NextBytes : buffer:byte[] -> unit
  member NextDouble : unit -> float

Full name: System.Random

--------------------
System.Random() : unit
System.Random(Seed: int) : unit
val port : int
System.Random.Next() : int
System.Random.Next(maxValue: int) : int
System.Random.Next(minValue: int, maxValue: int) : int
val local : HttpBinding
module Http

from Suave
Multiple items
module HttpBinding

from Suave.Http

--------------------
type HttpBinding =
  {scheme: Protocol;
   socketBinding: SocketBinding;}
  override ToString : unit -> string
  member uri : path:string -> query:string -> Uri
  static member scheme_ : Property<HttpBinding,Protocol>
  static member socketBinding_ : Property<HttpBinding,SocketBinding>

Full name: Suave.Http.HttpBinding
val mkSimple : scheme:Protocol -> ip:string -> port:int -> HttpBinding

Full name: Suave.Http.HttpBinding.mkSimple
union case Protocol.HTTP: Protocol
val logger : Logging.Logger
namespace Suave.Logging
module Loggers

from Suave.Logging
val saneDefaultsFor : level:Logging.LogLevel -> Logging.Logger

Full name: Suave.Logging.Loggers.saneDefaultsFor
type LogLevel =
  | Verbose
  | Debug
  | Info
  | Warn
  | Error
  | Fatal
  interface IEquatable<LogLevel>
  interface IComparable<LogLevel>
  interface IComparable
  override Equals : other:obj -> bool
  override GetHashCode : unit -> int
  member ToInt : unit -> int
  override ToString : unit -> string
  static member FromInt : i:int -> LogLevel
  static member FromString : str:string -> LogLevel
  static member ( > ) : a:IComparable<LogLevel> * b:LogLevel -> bool
  static member ( >= ) : a:IComparable<LogLevel> * b:LogLevel -> bool
  static member ( < ) : a:IComparable<LogLevel> * b:LogLevel -> bool
  static member ( <= ) : a:IComparable<LogLevel> * b:LogLevel -> bool

Full name: Suave.Logging.LogLevel
union case Logging.LogLevel.Error: Logging.LogLevel
val config : SuaveConfig
val defaultConfig : SuaveConfig

Full name: Suave.Web.defaultConfig
val started : Async<Tcp.StartedData option []>
val start : Async<unit>
val startWebServerAsync : config:SuaveConfig -> webpart:WebPart -> Async<Tcp.StartedData option []> * Async<unit>

Full name: Suave.Web.startWebServerAsync
val running : Tcp.StartedData option []
member Event.Trigger : arg:'T -> unit
static member Async.Start : computation:Async<unit> * ?cancellationToken:System.Threading.CancellationToken -> unit
namespace System.Net
namespace System.Net.Sockets
Multiple items
type SocketException =
  inherit Win32Exception
  new : unit -> SocketException + 1 overload
  member ErrorCode : int
  member Message : string
  member SocketErrorCode : SocketError

Full name: System.Net.Sockets.SocketException

--------------------
System.Net.Sockets.SocketException() : unit
System.Net.Sockets.SocketException(errorCode: int) : unit
Raw view Test code New version

More information

Link:http://fssnip.net/7Po
Posted:8 years ago
Author:Tomas Petricek
Tags: http , server , suave