Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6611269
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T19:56:56+00:00 2026-05-25T19:56:56+00:00

import Network.Socket import Control.Monad import Network import System.Environment (getArgs) import System.IO import Control.Concurrent (forkIO)

  • 0
import Network.Socket
import Control.Monad
import Network
import System.Environment (getArgs)
import System.IO
import Control.Concurrent (forkIO)

main :: IO ()
main = withSocketsDo $ do
   putStrLn ("up top\n")
   [portStr] <- getArgs
   sock' <- socket AF_INET Stream defaultProtocol 
   let port = fromIntegral (read portStr :: Int)
       socketAddress = SockAddrInet port 0000 
   bindSocket sock' socketAddress
   listen sock' 1
   putStrLn $ "Listening on " ++ (show port)
   (sock, sockAddr) <- Network.Socket.accept sock'
   handle <- socketToHandle sock ReadWriteMode
   sockHandler sock handle
-- hClose handle putStrLn ("close handle\n")

sockHandler :: Socket -> Handle -> IO ()
sockHandler sock' handle = forever $ do
    hSetBuffering handle LineBuffering
    forkIO $ commandProcessor handle

commandProcessor :: Handle -> IO ()
commandProcessor  handle = do
    line <- hGetLine handle
    let (cmd:arg) = words line
    case cmd of
        "echo" -> echoCommand handle arg 
        "add" -> addCommand handle arg 
        _ -> do hPutStrLn handle "Unknown command"
 

echoCommand :: Handle -> [String] -> IO ()
echoCommand handle arg = do
    hPutStrLn handle (unwords arg)

addCommand :: Handle -> [String] -> IO ()
addCommand handle [x,y] = do
    hPutStrLn handle $ show $ read x + read y
addCommand handle _ = do
    hPutStrLn handle "usage: add Int Int"

I’m noticing some quirks in it’s behavior, but the one I want to address for the moment is what happens when a client disconnects with the server. When that happens, the server throws the following exception endlessly, and will not respond to further client connections.

strawboss: : hGetLine: end of file

I’ve tried flushing the handle, and closing the handle. I think that closing the handle is the right thing to do, but I cannot figure out where te correct place to close the handle is. So my first question is: Is the solution to this problem a judicious hClose placement in the code? If not, where does the problem lie?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T19:56:56+00:00Added an answer on May 25, 2026 at 7:56 pm

    There are several problems in this code. The main one is that you have your forever in the wrong place. What I assume you want is to endlessly accept connections, and deal with them in sockHandler, whereas your code currently only ever accepts a single connection, and then endlessly forks off worker threads to handle that single connection in parallel. This causes the mess you’re experiencing.

    sockHandler sock' handle = forever $ do
        ...
        forkIO $ commandProcessor handle
    

    Instead, you’ll want to move the forever to main:

    forever $ do
        (sock, sockAddr) <- Network.Socket.accept sock'
        handle <- socketToHandle sock ReadWriteMode
        sockHandler sock handle
    

    However, you will still get an exception when a client disconnects, because you’re not checking if the connection has ended before calling hGetLine. We can fix this by adding using hIsEOF. You can then safely do a hClose on the handle once you know you’re done with it.

    Here’s your code with these modifications in place. I also took the liberty of restructuring your code a little.

    import Network.Socket
    import Control.Monad
    import Network
    import System.Environment (getArgs)
    import System.IO
    import Control.Concurrent (forkIO)
    import Control.Exception (bracket)
    
    main :: IO ()
    main = withSocketsDo $ do
       putStrLn ("up top\n")
       [port] <- getArgs
       bracket (prepareSocket (fromIntegral $ read port))
               sClose
               acceptConnections
    
    prepareSocket :: PortNumber -> IO Socket
    prepareSocket port = do
       sock' <- socket AF_INET Stream defaultProtocol 
       let socketAddress = SockAddrInet port 0000 
       bindSocket sock' socketAddress
       listen sock' 1
       putStrLn $ "Listening on " ++ (show port)
       return sock'
    
    acceptConnections :: Socket -> IO ()
    acceptConnections sock' = do
       forever $ do
           (sock, sockAddr) <- Network.Socket.accept sock'
           handle <- socketToHandle sock ReadWriteMode
           sockHandler sock handle
    
    sockHandler :: Socket -> Handle -> IO ()
    sockHandler sock' handle = do
        hSetBuffering handle LineBuffering
        -- Add the forkIO back if you want to allow concurrent connections.
        {- forkIO  $ -}
        commandProcessor handle
        return ()
    
    commandProcessor :: Handle -> IO ()
    commandProcessor handle = untilM (hIsEOF handle) handleCommand >> hClose handle
      where
        handleCommand = do
            line <- hGetLine handle
            let (cmd:arg) = words line
            case cmd of
                "echo" -> echoCommand handle arg 
                "add" -> addCommand handle arg 
                _ -> do hPutStrLn handle "Unknown command"
    
    echoCommand :: Handle -> [String] -> IO ()
    echoCommand handle arg = do
        hPutStrLn handle (unwords arg)
    
    addCommand :: Handle -> [String] -> IO ()
    addCommand handle [x,y] = do
        hPutStrLn handle $ show $ read x + read y
    addCommand handle _ = do
        hPutStrLn handle "usage: add Int Int"
    
    untilM cond action = do
       b <- cond
       if b
         then return ()
         else action >> untilM cond action
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider this code: import socket store = [] scount = 0 while True: scount+=1
I've set up this simple script on my local machine: #!/usr/bin/python import socket from
I'm using Python's urllib2 to send an HTTP post: import socket, urllib, urllib2 socket.setdefaulttimeout(15)
I'm trying to allow users to import their existing pictures to my social network.
I'm writing a web application that talks over network socket to a server that
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.io.FileReader; public class Main { public static void main(String[]
There is a socket method for getting the IP of a given network interface:
import sys words = { 1 : 'one', 2 : 'two', 3 : 'three',
I need to import a csv file into Firebird and I've spent a couple
How can you import a foxpro DBF file in SQL Server?

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.