Byte Order Problems When reading constants in Haskell

  Kiến thức lập trình

When I run the code:

import Control.Applicative
import Control.Concurrent
import Control.Monad
import Network.Socket
import System.Environment
import System.IO
import Numeric (showHex)
import qualified System.ByteOrder as BO
import qualified Data.ByteString as B
import Data.ByteString (toStrict)
import Data.ByteString.Conversion (toByteString)
import Data.Word (Word16)



prettyPrint :: B.ByteString -> String
prettyPrint = concatMap ((x -> "0x"++x++" ") . flip showHex "") . B.unpack

main :: IO ()
main = withSocketsDo $ do
  port <- toEnum . read . head <$> getArgs 
  newSocket <- socket AF_INET Stream defaultProtocol 
  setSocketOption newSocket ReuseAddr 1
  bindSocket newSocket $ SockAddrInet port iNADDR_ANY
  listen newSocket 2
  runServer echo newSocket

runServer :: (String -> String) -> Socket -> IO()
runServer f s = forever $ do
  (usableSocket,_) <- accept s
  forkIO $ interactWithSocket f usableSocket 

interactWithSocket :: (String -> String) -> Socket -> IO()
interactWithSocket f s = do 
  handle <- socketToHandle s ReadWriteMode
  forever $ f <$> recv handle 1024 >>= process >> putStrLn (prettyPrint msg)

process :: ByteString -> IO ()
process input = let command = B.take 2 $ B.take 2 input in
                  putStrLn (prettyPrint)

I get the output:

0x1 0x11 0x80 0x5 0x0 0x0 0x0 0x0
0x80 0x5

After running uspip --tcp-port 1024 list -r localhost as expected.
But when I replace the main function with

main = putStrLn $ prettyPrint $ toStrict (toByteString (BO.toBigEndian (fromInteger 0x8005) :: Word16))

I am getting the output:

0x31 0x34 0x30 0x38

Note I am trying to write a https://docs.kernel.org/usb/usbip_protocol.html server.

I thus I need to be able to store the command codes like 0x8005 in constants for know what commands are being received.

LEAVE A COMMENT