Created
March 15, 2015 01:01
-
-
Save ekepes/67423b6182b81e93bf08 to your computer and use it in GitHub Desktop.
An attempt to port the TcpReactorServer in Helios to F#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Port of https://github.com/helios-io/helios/blob/dev/samples/Helios.Samples.TcpReactorServer/Program.cs | |
open System | |
open System.Net | |
open System.Text | |
open Helios.Net | |
open Helios.Reactor | |
open Helios.Reactor.Bootstrap | |
open Helios.Reactor.Tcp | |
open Helios.Topology | |
let serverPrint (node :INode) message = | |
printfn "[%A] %A:%A: %A" DateTime.UtcNow node.Host node.Port message | |
let ReceiveData : ReceivedDataCallback = | |
new ReceivedDataCallback( | |
fun (data :NetworkData) (connection :IConnection) -> | |
let node = connection.RemoteHost | |
serverPrint node (sprintf "recieved %A bytes" data.Length) | |
let str = Encoding.UTF8.GetString(data.Buffer).Trim() | |
if str.Trim().Equals("close") then | |
connection.Close() | |
else | |
serverPrint node (sprintf "recieved \"%A\"" str) | |
serverPrint node (sprintf "sending \"%A\" back to %A:%A" str node.Host node.Port) | |
let sendBytes = Encoding.UTF8.GetBytes(str + Environment.NewLine) | |
let mutable response = new NetworkData() | |
response.Buffer <- sendBytes | |
response.Length <- sendBytes.Length | |
response.RemoteHost <- node | |
connection.Send response) | |
[<EntryPoint>] | |
let main argv = | |
let port = 1337 | |
let ip = IPAddress.Any; | |
printfn "Starting echo server..." | |
printfn "Will begin listening for requests on %A:%A" ip port | |
let bootstrapper = ServerBootstrap().WorkerThreads(2).SetTransport(TransportType.Tcp).Build() | |
let node = NodeBuilder.BuildNode() | |
node.Host <- ip | |
node.Port <- port | |
let reactor = bootstrapper.NewReactor node | |
reactor.add_OnConnection(fun node channel -> | |
serverPrint node (sprintf "Accepting connection from... %A:%A" node.Host node.Port) | |
channel.BeginReceive(ReceiveData)) | |
reactor.add_OnDisconnection(fun reason address -> | |
serverPrint address.RemoteHost (sprintf "Closed connection to... %A:%A [Reason:%A]" address.RemoteHost.Host address.RemoteHost.Port reason.Type)) | |
reactor.Start() | |
Console.ReadKey() |> ignore | |
0 // return an integer exit code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It will start up and accept connections, but doesn't seem to handle receiving data.