Hash2Pub/demoserver.hs

39 lines
1.4 KiB
Haskell
Raw Permalink Normal View History

{-# LANGUAGE OverloadedStrings #-}
2020-04-05 19:58:33 +02:00
module Main where
2020-04-05 19:58:33 +02:00
import Network.Socket hiding (send, sendTo, recv, recvFrom)
import Network.Socket.ByteString
import Control.Concurrent
import Control.Exception
import Control.Monad (forever)
import System.IO (
IOMode (ReadWriteMode)
)
import qualified Data.ByteString as BS
main = do
sock <- socket AF_INET6 Datagram defaultProtocol
2020-04-09 00:38:55 +02:00
setSocketOption sock IPv6Only 1
-- lookup destination to get a SockAddr
let hints = defaultHints { addrFamily = AF_INET6, addrSocketType = Datagram}
2020-04-05 19:58:33 +02:00
serverAddr <- addrAddress . head <$> getAddrInfo (Just hints) (Just "::1") (Just "7331")
print serverAddr
bind sock serverAddr
print sock
forever $ do
receivedStuff <- recvFrom sock 65535 -- blocks
2020-04-05 19:58:33 +02:00
forkIO $ bracket newSendSocket close (serveReceive receivedStuff)
2020-04-05 19:58:33 +02:00
serveReceive :: (BS.ByteString, SockAddr) -> Socket -> IO ()
serveReceive (msg, fromAddr) sendSocket = do
2020-04-05 19:58:33 +02:00
print sendSocket
putStrLn $ "Got message " ++ show msg ++ " from " ++ show fromAddr
-- important: as new socket sends from a different port, the receiving client must use an unconnected socket!
2020-04-05 19:58:33 +02:00
sentBytes <- sendTo sendSocket ("Hi, thx for " `BS.append` msg) fromAddr
putStrLn $ "sent response of " ++ show sentBytes ++ "bytes"
return ()
newSendSocket :: IO Socket
newSendSocket = socket AF_INET6 Datagram defaultProtocol