Simple Haskell networking example
Created: 2025-06-06, never modified since
This example shows how to listen on a Unix socket in Haskell.
This example is useful for people who want to interface with IPC, and can be modified to make and recieve TCP connections.
To adapt this to use TCP connections, use a combination of `defaultHints` and `getAddrInfo`, and use the address from `getAddrInfo` in the variable `addr` instead. There's a quite messy example in the the `network` docs.
Relevant docs:
Hoogle is your friend :)
discord-rpc-hijacker.cabal:
executable discord-rpc-hijacker
import: warnings
main-is: Main.hs
-- other-modules:
-- other-extensions:
build-depends: base ^>=4.21.0.0,
network ^>=3.2.7.0,
bytestring ^>= 0.12.2.0
hs-source-dirs: app
default-language: Haskell2010
app/Main.hs:
module Main where
import qualified Data.ByteString.Char8 as C
import Network.Socket
import Network.Socket.ByteString (recv, sendAll)
import Control.Monad
messagePrintLoop :: Socket -> IO ()
messagePrintLoop conn = forever $ do {
msg <- recv conn 1024;
C.putStr msg;
}
socketLoop :: Socket -> IO ()
socketLoop sock = forever $ do {
(conn, conn_addr) <- accept sock;
sendAll conn $ C.pack "Hewwow\n";
putStrLn "Printing incomming messges:";
messagePrintLoop conn;
}
main :: IO ()
main =
let addr = SockAddrUnix "a-socket" in
do {
sock <- socket AF_UNIX Stream defaultProtocol;
bind sock addr;
listen sock 1;
socketLoop sock;
}
---
Authors:
- ludv
Except where otherwise noted, this entry, including any assets or other pages under the same URL path (/entries/haskell-networking-example/), is marked with CC0 1.0.