prototype of server and client successfully communicating via unconnected Datagram sockets

This commit is contained in:
Trolli Schmittlauch 2020-04-06 14:19:34 +02:00
parent 6958fc2f98
commit 357152da46
2 changed files with 28 additions and 1 deletions

26
Hash2Pub/democlient.hs Normal file
View file

@ -0,0 +1,26 @@
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Network.Socket hiding (send, sendTo, recv, recvFrom)
import Network.Socket.ByteString
import Control.Monad (forever)
import System.IO (
IOMode (ReadWriteMode)
)
import qualified Data.ByteString as BS
import qualified Data.ByteString.UTF8 as BSU
main = do
sock <- socket AF_INET6 Datagram defaultProtocol
-- lookup destination to get a SockAddr
let hints = defaultHints { addrFamily = AF_INET6, addrSocketType = Datagram}
destAddr <- addrAddress . head <$> getAddrInfo (Just hints) (Just "::1") (Just "7331")
forever $ do
inp <- getLine
sendTo sock (BSU.fromString inp) destAddr
print "Yeah, sent sth."
-- important: as the socket is unconnected, it also accepts replies from a different source port
(msg, fromAddr) <- recvFrom sock 65535
putStrLn $ "Woop, received " ++ show msg ++ " from " ++ show fromAddr
return ()

View file

@ -9,12 +9,12 @@ import Control.Exception
import Control.Monad (forever)
import System.IO (
IOMode (ReadWriteMode)
, hPutStrLn
)
import qualified Data.ByteString as BS
main = do
sock <- socket AF_INET6 Datagram defaultProtocol
-- lookup destination to get a SockAddr
let hints = defaultHints { addrFamily = AF_INET6, addrSocketType = Datagram}
serverAddr <- addrAddress . head <$> getAddrInfo (Just hints) (Just "::1") (Just "7331")
print serverAddr
@ -28,6 +28,7 @@ serveReceive :: (BS.ByteString, SockAddr) -> Socket -> IO ()
serveReceive (msg, fromAddr) sendSocket = do
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!
sentBytes <- sendTo sendSocket ("Hi, thx for " `BS.append` msg) fromAddr
putStrLn $ "sent response of " ++ show sentBytes ++ "bytes"
return ()