Haskell sendFile function

388 views Asked by At

Where can I find some actual examples of sendFile function (Network.Socket.SendFile lib). When I tried to do all by official manual, I got an error:

Exception: {file path}: withFd: resource vanished (Broken pipe)

is it some light-sense example of function usage?

Here is source:

withSocketsDo $ do                                                                                                                                              
                sock <- socket AF_INET Stream defaultProtocol                                                                                                           
                bindSocket sock (SockAddrInet 1212 0)
                sendFile sock "/some/path/to/file"
1

There are 1 answers

0
jamshidh On

Here is some code that I got to work.

import Network.Socket.SendFile
import Network.Socket

main = withSocketsDo $ do
    sock <- socket AF_INET Stream defaultProtocol            
    addr <- inet_addr "127.0.0.1"
    connect sock (SockAddrInet 8080 addr)
    sendFile sock "some/path/to/file"

Here are the notes what is happening, and how to get it to work-

  1. You need to set up a server to accept the data. The simplest thing you can do (for testing purposes only) is use netcat. On my linux box, I started netcat by typing

    nc -l -p 8080

("-l" tells it to listen for a connection, -p specifies the port, which can be anything you have permission to bind to as long as it matches the port in the haskell program above)

  1. The withSocketsDo is only needed for Windows compatibility, but it doesn't hurt in other environments.

  2. You need to use connect instead of bind to connect to a server.

  3. Once you have compiled and runt he program, you should see the contents of the file in the terminal that started netcat (and the program will stop). If you run the haskell program without first starting the netcat server, you will get an error.