24 people like it.

TCP/IP Proxy

A minimal TCP/IP proxy implementation with F# asynchronous workflows

 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: 
28: 
29: 
30: 
31: 
32: 
open System.IO
open System.Threading
open System.Net
open System.Net.Sockets

let mirror (clientStream:Stream) (serverStream:Stream) = async {
    while true do
        let! onebyte = clientStream.AsyncRead(1)
        do! serverStream.AsyncWrite(onebyte) 
}

let proxy (clientStream:Stream) (serverStream:Stream) = 
    [| mirror clientStream serverStream; mirror serverStream clientStream |]
        |> Async.Parallel
        |> Async.RunSynchronously 
        
let stream (client:TcpClient) = client.GetStream()

let tcp_ip_proxy (sourceip,sourceport) (targetip,targetport) = 
    let server = new TcpListener(IPAddress.Parse(sourceip),sourceport)
    server.Start()
    while true do 
        let client = server.AcceptTcpClient()
        let up = new TcpClient(targetip,targetport)
        let t = new Thread(ThreadStart(fun _ -> 
            try      
                stream (client) |> proxy <| stream(up) |> ignore 
            with |_ -> ())
        , IsBackground = true)
        t.Start()   

tcp_ip_proxy ("127.0.0.1",8080) ("66.249.81.104",80)
namespace System
namespace System.IO
namespace System.Threading
namespace System.Net
namespace System.Net.Sockets
val mirror : clientStream:Stream -> serverStream:Stream -> Async<unit>

Full name: Script.mirror
val clientStream : Stream
type Stream =
  inherit MarshalByRefObject
  member BeginRead : buffer:byte[] * offset:int * count:int * callback:AsyncCallback * state:obj -> IAsyncResult
  member BeginWrite : buffer:byte[] * offset:int * count:int * callback:AsyncCallback * state:obj -> IAsyncResult
  member CanRead : bool
  member CanSeek : bool
  member CanTimeout : bool
  member CanWrite : bool
  member Close : unit -> unit
  member CopyTo : destination:Stream -> unit + 1 overload
  member Dispose : unit -> unit
  member EndRead : asyncResult:IAsyncResult -> int
  ...

Full name: System.IO.Stream
val serverStream : Stream
val async : AsyncBuilder

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async
val onebyte : byte []
member Stream.AsyncRead : count:int -> Async<byte []>
member Stream.AsyncRead : buffer:byte [] * ?offset:int * ?count:int -> Async<int>
member Stream.AsyncWrite : buffer:byte [] * ?offset:int * ?count:int -> Async<unit>
val proxy : clientStream:Stream -> serverStream:Stream -> unit []

Full name: Script.proxy
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<'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.Parallel : computations:seq<Async<'T>> -> Async<'T []>
static member Async.RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:CancellationToken -> 'T
val stream : client:TcpClient -> NetworkStream

Full name: Script.stream
val client : TcpClient
Multiple items
type TcpClient =
  new : unit -> TcpClient + 3 overloads
  member Available : int
  member BeginConnect : host:string * port:int * requestCallback:AsyncCallback * state:obj -> IAsyncResult + 2 overloads
  member Client : Socket with get, set
  member Close : unit -> unit
  member Connect : remoteEP:IPEndPoint -> unit + 3 overloads
  member Connected : bool
  member EndConnect : asyncResult:IAsyncResult -> unit
  member ExclusiveAddressUse : bool with get, set
  member GetStream : unit -> NetworkStream
  ...

Full name: System.Net.Sockets.TcpClient

--------------------
TcpClient() : unit
TcpClient(localEP: IPEndPoint) : unit
TcpClient(family: AddressFamily) : unit
TcpClient(hostname: string, port: int) : unit
TcpClient.GetStream() : NetworkStream
val tcp_ip_proxy : sourceip:string * sourceport:int -> targetip:string * targetport:int -> unit

Full name: Script.tcp_ip_proxy
val sourceip : string
val sourceport : int
val targetip : string
val targetport : int
val server : TcpListener
Multiple items
type TcpListener =
  new : localEP:IPEndPoint -> TcpListener + 2 overloads
  member AcceptSocket : unit -> Socket
  member AcceptTcpClient : unit -> TcpClient
  member AllowNatTraversal : allowed:bool -> unit
  member BeginAcceptSocket : callback:AsyncCallback * state:obj -> IAsyncResult
  member BeginAcceptTcpClient : callback:AsyncCallback * state:obj -> IAsyncResult
  member EndAcceptSocket : asyncResult:IAsyncResult -> Socket
  member EndAcceptTcpClient : asyncResult:IAsyncResult -> TcpClient
  member ExclusiveAddressUse : bool with get, set
  member LocalEndpoint : EndPoint
  ...

Full name: System.Net.Sockets.TcpListener

--------------------
TcpListener(localEP: IPEndPoint) : unit
TcpListener(localaddr: IPAddress, port: int) : unit
Multiple items
type IPAddress =
  new : newAddress:int64 -> IPAddress + 2 overloads
  member Address : int64 with get, set
  member AddressFamily : AddressFamily
  member Equals : comparand:obj -> bool
  member GetAddressBytes : unit -> byte[]
  member GetHashCode : unit -> int
  member IsIPv6LinkLocal : bool
  member IsIPv6Multicast : bool
  member IsIPv6SiteLocal : bool
  member IsIPv6Teredo : bool
  ...

Full name: System.Net.IPAddress

--------------------
IPAddress(newAddress: int64) : unit
IPAddress(address: byte []) : unit
IPAddress(address: byte [], scopeid: int64) : unit
IPAddress.Parse(ipString: string) : IPAddress
TcpListener.Start() : unit
TcpListener.Start(backlog: int) : unit
TcpListener.AcceptTcpClient() : TcpClient
val up : TcpClient
val t : Thread
Multiple items
type Thread =
  inherit CriticalFinalizerObject
  new : start:ThreadStart -> Thread + 3 overloads
  member Abort : unit -> unit + 1 overload
  member ApartmentState : ApartmentState with get, set
  member CurrentCulture : CultureInfo with get, set
  member CurrentUICulture : CultureInfo with get, set
  member DisableComObjectEagerCleanup : unit -> unit
  member ExecutionContext : ExecutionContext
  member GetApartmentState : unit -> ApartmentState
  member GetCompressedStack : unit -> CompressedStack
  member GetHashCode : unit -> int
  ...

Full name: System.Threading.Thread

--------------------
Thread(start: ThreadStart) : unit
Thread(start: ParameterizedThreadStart) : unit
Thread(start: ThreadStart, maxStackSize: int) : unit
Thread(start: ParameterizedThreadStart, maxStackSize: int) : unit
type ThreadStart =
  delegate of unit -> unit

Full name: System.Threading.ThreadStart
val ignore : value:'T -> unit

Full name: Microsoft.FSharp.Core.Operators.ignore
Thread.Start() : unit
Thread.Start(parameter: obj) : unit

More information

Link:http://fssnip.net/3t
Posted:6 years ago
Author:Ademar Gonzalez
Tags: tcp-ip , networking , async