Skip to content

Instantly share code, notes, and snippets.

@kreed131
Created July 22, 2011 20:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kreed131/1100407 to your computer and use it in GitHub Desktop.
Save kreed131/1100407 to your computer and use it in GitHub Desktop.
Simple TCP client on Haskell
---
-- kreed131.blogspot.com/2011/07/tcp.html
---
import Network.Socket hiding (send, sendTo, recv, recvFrom)
import Network.Socket.ByteString (send, recv)
import qualified Data.ByteString.Char8 as B8
import System.Environment (getArgs)
main :: IO ()
main = do
[host', port'] <- getArgs
client host' (read port' :: Int)
client :: String -> Int -> IO ()
client host port = withSocketsDo $ do
addrInfo <- getAddrInfo Nothing (Just host) (Just $ show port)
let serverAddr = head addrInfo
sock <- socket (addrFamily serverAddr) Stream defaultProtocol
connect sock (addrAddress serverAddr)
msgSender sock
sClose sock
msgSender :: Socket -> IO ()
msgSender sock = do
msg <- B8.getLine
send sock msg
rMsg <- recv sock 10
B8.putStrLn rMsg
if msg == B8.pack "q" then putStrLn "Disconnected!" else msgSender sock
Copy link

ghost commented Jun 10, 2016

Fails to connect, can be fixed by replacing "localhost" with "127.0.0.1".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment