A TCP server and its client in one program

The complete source of networkTypes_tcp_ready.ek9, compiled by the EK9 compiler. Shown on networkTypes.html.

#!ek9
defines module site.networkTypes.tcpReady

  defines function

    echo() is TCPHandler
      ->
        input as StringInput
        output as StringOutput
      while input?
        output.println(`echo:${input.next()}`)

  defines program

    TCPServerAndItsClient()
      stdout <- Stdout()
      props <- NetworkProperties(port: 0, backlog: 2, maxConcurrent: 2, localOnly: true)

      try
        -> tcpServer <- TCP(props)
        client <- (stdout, props) is TCPReadyHandler as function
          loopback <- Networking().loopbackV4()
          try
            -> connection <- TCP(NetworkProperties(loopback, props.port)).connect()
            if connection?
              connection.output().println("hello")
              stdout.println(`Received [${connection.input().next()}]`)
          server.stop()

        if tcpServer.acceptUntilComplete(echo, client)
          stdout.println(`Served until the client completed, server still set ${tcpServer?}`)
      stdout.println("The try has closed the server")

Download networkTypes_tcp_ready.ek9

Output

Received [echo:hello]
Served until the client completed, server still set true
The try has closed the server