/* * Copyright 2025 Ry Wiese * * Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE.md file. */////// Effect for connecting to TCP servers, and its functions.///pubmod Net.TcpConnect {use IoError.ErrorKinduse IoError.IoErroruse Net.IpAddruse Net.TcpSocketuse Net.TcpSocket.TcpSocketimport java.net.InetAddressimport java.net.Socketimport java.io.IOException////// Effect for connecting to TCP servers.///pubeffTcpConnect {/// Opens a TCP connection to the given `ip` address and `port`.defconnect(ip: IpAddr, port: Int16): Result[IoError, TcpSocket] }////// Handles the `TcpConnect` effect of the given function `f`.////// In other words, re-interprets the `TcpConnect` effect using the `IO` effect.///pubdefhandle(f: a -> b \ ef): a -> b \ (ef - TcpConnect) + IO = x ->run {f(x) } withhandlerTcpConnect {defconnect(ip, port, k) = {try {letinet: InetAddress = InetAddress.getByAddress(IpAddr.toBytes(ip));letsocket = new Socket(inet, Int16.toInt32(port));letinputStream = socket.getInputStream();letoutputStream = socket.getOutputStream();k(Ok(TcpSocket(socket, inputStream, outputStream))) } catch {caseex: IOException => k(Err(IoError(ErrorKind.Other, ex.getMessage()))) } } }////// Runs the `TcpConnect` effect of the given function `f`.////// In other words, re-interprets the `TcpConnect` effect using the `IO` effect.///@DefaultHandlerpubdefrunWithIO(f: Unit -> a \ ef): a \ (ef - TcpConnect) + IO = handle(f)()}