Search code examples
socketshaskelltcpserver

Starting TCP server in Haskell


I am trying to create a TCP server in Haskell from the example provided on haskell.org. When I run the code from the terminal with ghc run Main.hs, I get:

[1 of 1] Compiling Main             ( Main.hs, Main.o )
Linking Main.exe ...

After which it closes.

Code

module Main where 
    import Network.Socket
    import Network.Socket.ByteString
    import qualified Data.ByteString.Char8 as C

    main::IO()
    main=do
        sock<-socket AF_INET Stream 0
        bind sock (SockAddrInet 8100 iNADDR_ANY)
        listen sock 2
        mainloop sock


    mainloop::Socket->IO()
    mainloop sock=do
        conn<-accept sock
        runConn conn
        mainloop sock


    runConn::(Socket,SockAddr)->IO()
    runConn (sock,_)=do
        Network.Socket.ByteString.send sock (C.pack "hello")
        close sock

I first assumed the server might somehow run in the backgroud so I tested it with the Simple Web Socket Client - browser extension and nada.

Tested url
ws://localhost:8100


Solution

  • You need to execute your binaries after compiling them: ./Main on linux or Main.exe on windows.

    Then you can request your server thanks to telnet localhost 8100

    telnet localhost 8100 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. helloConnection closed by foreign host.