prototype of server and client successfully communicating via unconnected Datagram sockets
This commit is contained in:
parent
6958fc2f98
commit
357152da46
26
Hash2Pub/democlient.hs
Normal file
26
Hash2Pub/democlient.hs
Normal 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 ()
|
|
@ -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 ()
|
||||
|
|
Loading…
Reference in a new issue