2020-04-04 21:27:34 +02:00
|
|
|
{-# LANGUAGE OverloadedStrings #-}
|
2020-04-05 19:58:33 +02:00
|
|
|
|
2020-04-04 21:27:34 +02:00
|
|
|
module Main where
|
|
|
|
|
2020-04-05 19:58:33 +02:00
|
|
|
import Network.Socket hiding (send, sendTo, recv, recvFrom)
|
2020-04-04 21:27:34 +02:00
|
|
|
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
|
2020-04-06 14:19:34 +02:00
|
|
|
-- lookup destination to get a SockAddr
|
2020-04-04 21:27:34 +02:00
|
|
|
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")
|
2020-04-04 21:27:34 +02:00
|
|
|
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-04 21:27:34 +02:00
|
|
|
|
2020-04-05 19:58:33 +02:00
|
|
|
serveReceive :: (BS.ByteString, SockAddr) -> Socket -> IO ()
|
2020-04-04 21:27:34 +02:00
|
|
|
serveReceive (msg, fromAddr) sendSocket = do
|
2020-04-05 19:58:33 +02:00
|
|
|
print sendSocket
|
2020-04-04 21:27:34 +02:00
|
|
|
putStrLn $ "Got message " ++ show msg ++ " from " ++ show fromAddr
|
2020-04-06 14:19:34 +02:00
|
|
|
-- 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"
|
2020-04-04 21:27:34 +02:00
|
|
|
return ()
|
|
|
|
|
|
|
|
newSendSocket :: IO Socket
|
|
|
|
newSendSocket = socket AF_INET6 Datagram defaultProtocol
|