[Haskell-cafe] Trying to write a TCP proxy

John Ky newhoggy at gmail.com
Thu Sep 21 06:52:58 EDT 2006


Hi all,

Thanks for all your help.

I finally realised that hGetLine strips out the "\n" newline character
so when I forward the line to the server, I need to append it again.

Here's my implementation.

-John

> main = proxyServe

> proxyServe = withSocketsDo $ do
>   socket <- listenOn $ PortNumber 8082
>   acceptConnection socket

> acceptConnection socket = do
>   (handleToClient, hostName, portNumber) <- accept socket
>   handleToServer <- connectTo "127.0.0.1" (PortNumber 8080)
>   hSetBuffering handleToClient LineBuffering
>   hSetBuffering handleToServer LineBuffering
>   putStrLn $ "Socket accepted from " ++ hostName
>   forkIO (clientToServer handleToClient handleToServer)
>   forkIO (serverToClient handleToClient handleToServer)
>   acceptConnection socket

> clientToServer handleToClient handleToServer = do
>   putStrLn "Streaming from client to server"
>   eof <- hIsEOF handleToClient
>   if not eof
>     then do
>       text <- hGetLine handleToClient
>       hPutStr handleToServer $ text ++ "\n"
>       hFlush handleToServer
>       putStr ("C: " ++ text ++ "\n")
>       clientToServer handleToClient handleToServer
>     else do
>       putStrLn "EOF from Client"
>       return ()

> serverToClient handleToClient handleToServer = do
>   putStrLn "Streaming from server to client"
>   eof <- hIsEOF handleToClient
>   if not eof
>     then do
>       text <- hGetContents handleToServer
>       hPutStr handleToClient text
>       putStrLn $ "S: " ++ text
>       serverToClient handleToClient handleToServer
>     else do
>       putStrLn "EOF from Server"
>       return()


More information about the Haskell-Cafe mailing list