sockets,haskell,network-programming,io-monad , Refactor an IO recursive loop into a monad folding in Haskell

Refactor an IO recursive loop into a monad folding in Haskell


Tag: sockets,haskell,network-programming,io-monad

I writing a tcp server, and here's my main loop method:

serverLoop :: Socket -> IO ()
serverLoop sock = do
    (conn, _) <- accept sock
    forkIO $ handleConn conn
    serverLoop sock

(Note: handleConn :: Socket -> IO () is a function specific to my program.)

I would like to refactor that into a more monadic way, here's my tentative:

serverLoop :: Socket -> IO ()
serverLoop sock = foldl1 (>>) $ map go $ repeat sock
     where go sock = (accept sock) >>= (forkIO . handleConn . fst) >> return ()

But this makes the program crash as soon as I start sending data through the socket.

Here are my questions: why? what's the fix for that?


The idiomatic way to repeat the same action over and over again forever is forever

serverLoop :: Socket -> IO ()
serverLoop sock = forever $ do
    (conn, _) <- accept sock
    forkIO $ handleConn conn


logical expression evaluator Haskell

I wrote the following logical expression evaluator. It works for simple 2-member expressions, and it runs but produces a fault for expression containing other expressions as the second/first member. Here's my code. data Expression = Literal Bool | Operation Operator Expression Expression data Operator = AND | OR eval ::...

Fold over a heterogeneous, compile time, list

I have a list of heterogeneous types (or at least that's what I have in mind): data Nul data Bits b otherBits where BitsLst :: b -> otherBits -> Bits b otherBits NoMoreBits :: Bits b Nul Now, given an input type b, I want to go through all the...

How to identify a client connected to AF_UNIX socket?

What is the meaning of the "client address" in case of AF_UNIX sockets in Python? sock = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM ) sock.bind( "/tmp/sock" ) sock.listen( 1 ) while True: connection, client_address = sock.accept() print( client_address ) # prints : b'' Is there a way to obtain on the server side...

Keep track of loop without a counter

Say, I got a list which length can be odd or even. Every iteration , I remove two items from the list. If there is one or no item at the end, I end the execution. If I store (length list)/2 every loop, I will get e.g. [5,4,3...] for a...

UDP and TCP always use same IP for one client?

I've made a server (python, twisted) for my online game. Started with TCP, then later added constant updates with UDP (saw a big speed improvement). But now, I need to connect each UDP socket client with each TCP client. I'm doing this by having each client first connect to the...

Haskell: When declaring a class, how can I use a type variable that is not immediately in the constructors?

I want to define a function, <-? to check whether an element is in a list/set/map. module Test where import qualified Data.Map as Map import qualified Data.Set as Set class Memberable a where (<-?) :: b -> a -> Bool instance Memberable [x] where (<-?) = elem instance Memberable (Map.Map...

Haskell return lazy string from file IO

Here I'm back again with a (for me) really strange behaviour of my newest masterpiece... This code should read a file, but it doesn't: readCsvContents :: String -> IO ( String ) readCsvContents fileName = do withFile fileName ReadMode (\handle -> do contents <- hGetContents handle return contents ) main...

Making socket communication using bin_prot

I want to make Socket communication using bin_prot in OCaml. However, I can't find any detailed explanation or example to do that. I made Socket communication in the other way before, so I know the flow of it. Do you have good explanations or examples to make Socket communication using...

Haskell - generate and use the same random list

In Haskell, I'd like to generate a random list of Ints and use it throughout my program. My current solution causes the array to be created randomly each time I access/use it. How can I overcome this problem?...

First three items of a list in Haskell

I am very new to Haskell, and struggling a bit with a function here. The premise is simple enough: Run through a list, and combine each 3 items next to each other with another function and return a list with the results. The problem is to do it in a...

ZeroMQ pattern for multiple asynchronous requests to single endpoint

I'm using zmq to develop a distributed application having the following network topology: a client node that initiates a request and a server node that replies to requests. Since the client is a node.js application I can't block after a send call to wait the response, so the scenario is...

Creating Multi-user chat with sockets on python, how to handle the departure of the server?

I was trying to implement a multiuser chat (group chat) with socket on python. It basically works like this: Each messages that a user send is received by the server and the server sends it back to the rest of the users. The problem is that if the server close...

Should I use different WSAOVERLAPPED struct for WSASend and WSARecv?

I'm developing a server-client application using WinSock. Does using the same WSAOVERLAPPED with both WSASend and WSARecv works well? Should I use different WSAOVERLAPPED struct for WSASend and WSARecv?...

parameter error in python script & TOR proxy server

I am Noob in Python. My Boss instructed me to run this python script with TOR proxy server running. He told me to pass this parameter this way: python /Users/myfolder/ japan 1 222299 He configured it on MAC. I am using windows. So my parameter is this way:...

Coverity - overrun of struct type

I am getting the following error through the coverity tool - overrun-buffer-arg: Overrunning struct type in_addr of 4 bytes by passing it to a function which accesses it at byte offset 7 using argument "8UL". sample code: static u_long addr; static struct sockaddr_in remote_server; addr = inet_addr(remote_servername); memcpy((char *) &remote_server.sin_addr,...

How to “wrap” monadic return value

I have the following code: data APNSIdentifier = NoIdentifier | Identifier Word32 deriving (Show, Eq) newtype APNSItem = Item Put createNotificationIdentifierItem :: APNSIdentifier -> APNSItem <--- here createNotificationIdentifierItem (Identifier identifier) = do putWord8 3 putWord16be 4 putWord32be identifier How can I "wrap" the Put monad with an APNSItem? Do I...

How can I express foldr in terms of foldMap for type-aligned sequences?

I'm playing around with type-aligned sequences, and in particular I'm messing around with the idea of folding them. A foldable type-aligned sequence looks something like this: class FoldableTA fm where foldMapTA :: Category h => (forall b c . a b c -> h b c) -> fm a b...

Best practice for handling data types from 3rd party libraries in Haskell?

I'm just getting into my first real Haskell project of size (a web app), and I'm starting to run into issues with types from 3rd party libraries leaking all over my code. Here is a quick example: My Parser module imports Test.Parsec, and the exports a function (parseConfig) that returns...

Thread blocked indefinitely in an MVar operation

I have been attempting to debug a problem when using multiple MVars, however to no luck. My code uses two MVars: one to store the servers current state, and another to pass network events to and from the client threads. However after connecting and disconnecting several times, the server stops...

Haskell do clause with multiple monad types

I'm using a graphic library in Haskell called ThreePennyUI. In this library the main function returns a UI monad object. This causes me much headache as when I attempt to unpack IO values into local variables I receive errors complaining of different monad types. Here's an example of my problem:...

How does Frege generalize number literals?

It appears that Frege can evaluate 1/2 to return the Double value 0.5. The literal 1 is of type Int. It seems to be promoted to Double, which is a type in the Real class and thus knows the / operator. How does this happen? Is it using the Haskell...

Socket.IO message doesn't update Angular variable

I have a client-server setup with AngularJS running on the client. // Server.js var io = require('')(server); io.on('connection', function (socket) { socket.on('message', function (msg) { //console.log(msg); console.log(msg); io.emit('message', msg); }); }); As observed, it essentially emits a message events with the data stored in the variable msg. And then...

How to catch socket exceptions on TcpInboundGateway?

I'm using TcpInboundGateway from spring-integration for a socket client. In TcpInboundGateway.doOnMessage() the stream is send via the socket connection. If an exception occurs eg because the socket is closed, there is just a spring error log "Failed to send reply". BUT I'd like to handle those socket errors explicit. How...

websockets - reject a socket connection

I'm using ws as the socket library for my node.js library. so my question is, how can I reject a connection if the user doesn't pass the authorization process. var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({port: 6969}); wss.on('connection', function(socket){ // if the socket.upgradeReq.headers.cookie doesn't exists, reject the client...

apply a transformation with function inline

Starting from a simple case of "fold" (I used (+) but can be anything else): Prelude.foldl (+) 0 [10,20,30] is it possible apply an inline transformation similar to (that doesn't work): Prelude.foldl ((+) . (\x -> read x :: Int)) 0 ["10","20","30"] In case not, is there an alternative to...

Sails.js sockets. Good and bad sides. Difference with

So I am learning Sails.js at the moment and more specifically the integrated socket functionality of the framework. I do like the framework because it is very good for building APIs. My question is can you guys give me some comparison between and the sails sockets. I mean good...

ZMQ: No subscription message on XPUB socket for multiple subscribers (Last Value Caching pattern)

I implemented the Last Value Caching (LVC) example of ZMQ (, but can't get a 2nd subscriber to register at the backend. The first time a subscriber comes on board, the event[0] == b'\x01' condition is met and the cached value is sent, but the second subscriber (same topic) doesn't...

Sending files in socket programming tcp

I am trying to implement a simple file transfer. Below here is two methods that i have been testing: Method one: sending and receiving without splitting the file. I hard coded the file size for easier testing. sender: send(sock,buffer,107,NULL); //sends a file with 107 size receiver: char * buffer =...

How to get the socket's specific error reason when POLLERR happens?

When POLLERR comes up after polling, how can I determine the specific error reason?

Stopping condition on a recursive function - Haskell

So, I have this function which aims to align the text on the left without cutting words(only white spaces). However my problem is that I cannot find a stopping condition of the function and it goes infinitely. f n "" = "" --weak condition f n s = if n...

Replace all [ ] with {} - as short as possible [on hold]

Given the code below: import Data.List; main = (readLn :: IO [Integer]) >>= print . subsequences It takes a list of integers from standard input (for example [1,2,3]) and outputs something like: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] I want it to be like this: {},{1},{2},{1,2},{3},{1,3},{2,3},{1,2,3}} so my goal is to replace every [ and...

Haskell IO - read from standard input directly to list

Haskell IO system is super hard to understand for me so i have question : How to read from standard input to list ? I know that there is function getLine :: IO String and interact. But i do not know how to convert the input to list so I...

Use Sockets in multiple *.cpp files

As you can see in the Title box, I´d like to find a way how to use my sockets in multiple cpp files. #pragma comment(lib,"ws2_32.lib") void main() { WSADATA wsaData; WSAStartup(MAKEWORD(2,0), &wsaData); SOCKET slisten,client; slisten = socket(AF_INET,SOCK_STREAM, 0); //and so on... } This is the way I use the ws2_32.lib...

Java read bytes from Socket on Linux

I'm trying to send a file from my Windows machine to my Raspberry-Pi 2, and I have a client and a server. The client should be able to send a zip file over the network to my server on my linux machine. I know my client and server work on...

Sending a Mat object over socket from Java to Java

I understand Sockets over Java and sending Int,String,bytes etc over it. What i just want to know is that is there a way to decode a Mat object to byte array and then send it over java socket and then retrieve back the Mat object from the byte received? Till...

Implementing map on a tree using fold

I am trying to implement a map using fold. I could do so in Haskell data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show) foldTree :: Tree a -> b -> (b -> a -> b -> b) -> b foldTree EmptyTree d _ =...

When BSD socket reports that RST was received, if not everything was read yet

Lets imagine the following data sequence that was sent from the server to the client: [data] [data] [data] [FIN] [RST] And lets imagine that I'm doing the following on the client side (sockets are non-blocking): char buf[sizeof(data)]; for (;;) { rlen = recv(..., buf, sizeof(buf), ...); rerr = errno; slen...

Sockets make no sense?

I'm using the 'ws' library for Node.js. I can write code that sends data from my server to my client, posting a date and time update, and closes the socket when I click a button; var wss = new WebSocketServer({server: server}); console.log("WebSocket server created"); wss.on('connection', function(socket) { // SEND DATE...

Specified argument was out of the range of valid value to get data from network in c#

I am trying to send a command to a sensor and get the data from it using this code : const int PORT_NO = 3000; const string SERVER_IP = ""; //---listen at the specified IP and port no.--- IPAddress localAdd = IPAddress.Any; TcpListener listener = new TcpListener(localAdd, PORT_NO); Console.WriteLine("Listening..."); listener.Start();...

Python3:socket:TypeError: unsupported operand type(s) for %: 'bytes' and 'bytes'

I am try to use python socket package to implement an echo server. But it continuously occurs the error: TypeError: unsupported operand type(s) for %: 'bytes' and 'bytes', is there any errors in my code? here is the error: Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/",...

Using sockets to build real time chat for iOS?

If I wanted to build a real time chat app for iOS using Objective-C, what would be the best way of going about it?

Running a python script online for free (and accessing using ip and port) [closed]

I coded a python script to run a server for my iPhone messaging app. This app/server uses (currently) port 80 and ip localhost to run the server as I am running it on my computer so far. Now I need a host to run the script and allow me to...

Are the C functions recvfrom and sendto mutually exclusive?

I have one thread calling recvfrom with a timeout of 100 ms in a loop. Another thread calls sendto periodically. Does the sendto function wait until the recvfrom is released by the timeout (or a successful read) or does it send the data during that period of time....

Haskell make recipe fails for Paradox theorem prover using GHC

I am trying to install the paradox theorem prover sourced from here. When I run the makefile this is the command that runs: ghc -optl -static -lstdc++ -I../instantiate -I../minisat/current-base ../minisat/current-base/Solver.or ../minisat/current-base/Prop.or ../instantiate/MiniSatWrapper.or ../instantiate/MiniSatInstantiateClause.or -fglasgow-exts -O2 -static -threaded -main-is Paradox.Main.main --make Paradox.Main -o paradox And it results in several errors like...

Decremented value called in the recursion in Haskell

So, I have this function that aligns the text to the left for a given column width. I have already fixed some of its problems, but I am unable to make it not use the decremented parameter once it is called, but to return to the starting value of n....

Get each fibbonacci value in haskell

I'm learning haskell and I have the following code: fib a b = a : fib b (a + b) findFibSum = sum [x | x <- fib 1 2, mod x 2 == 0 && x < 100] If I run findFibSum nothing happens, it just sits there. Shouldn't...

How do I avoid writing this type of Haskell boilerplate code

I run into this situation often enough for it to be annoying. Let's say I have a sum type which can hold an instance of x or a bunch of other things unrelated to x - data Foo x = X x | Y Int | Z String | ...(other...

What type of database is the best for storing array or object like data [on hold]

I'm just curious what the best method would be if I'm trying to have a bot running on my Node server that I could play Blackjack against. But for multiple connected clients via sockets, each connected socket will have their own bot to play against but I need some way...

Combining Event and an attribute in threepenny-gui

I have an Event String which I want to sink into a textarea. This works fine, but now I want to combine the current value of a checkbox selection to this string. First I did this by using checkedChange of the checkbox which works, but has a problem. If the...

Merging socket request/response in a function

I'm trying to implement a client/server application communicating through sockets. The communication works fine and I can match and execute different functions. Most of the packets are from request / response type and are matched with a persistent sequence number. The problem I'm now stating is that I can't lead...