Thursday, May 10, 2007

A couple of silly examples

So having being mostly stumped on a few other ideas, I was rereading a textbook on OS design and saw that one of the exercises was to create an echo server. I thought I'd clean up one I had written in the past to learn the Network library and post it up here.

>port :: PortID
>port = PortNumber 6000

>main = withSocketsDo $ do
> sock <- listenOn port
> handler sock

>handler :: Socket -> IO ()
>handler s = do
> (h,_,_) <- accept s
> hSetBuffering h NoBuffering
> forkIO $ echo h
> handler s

>echo :: Handle -> IO ()
>echo h= do
> text <- liftM (filter (/='\r')) $ hGetLine h
> if text=="exit"
> then hClose h
> else do
> hPutStrLn h text
> echo h

If you run this and telnet to localhost 6000 you should be able to see it work. Actually writing this code was very simple and felt very intuitive.

Now, that's pretty simple and a nice start: now let's say we wanted a simple server that can handle connections, creating logins, and validating logins. The problem is that now the threads need to share some kind of information, and that makes things a lot more messy; however, Software Transactional Memory makes it a bit easier.

We'll take a very silly way to store usernames and passwords, as tuples in some list.

>type Login = (String,String)

Now our actual "database" of logins will be a STM TVar of a list of logins. For those unfamiliar with STM, I really do recommend reading some of the original papers. They're rather well written and clear in motivating how one would use STM. For now, all that matters is that a TVar is a mutable object that can be accessed and modified atomically.

>type DB = TVar [Login]

>main = do
> db <- newTVarIO []
> sock <- listenOn port
> handler sock db

>handler :: Socket -> DB -> IO ()
>handler s db = do
> (h,_,_) <- accept s
> hSetBuffering h NoBuffering
> forkIO $ loginServer h db
> handler s db

>loginServer :: Handle -> DB -> IO ()
>loginServer h db = do
> hPutStrLn h "Welcome to my server, log in or create an account: "
> hPutStrLn h "[0]:log in\n[1]:create account\n[2]:exit"
> choice <- liftM (filter (/='\r')) $ hGetLine h
> case choice of
> "0" -> validate h db
> "1" -> create h db
> "2" -> hClose h
> _ -> loginServer h db
>validate :: Handle -> DB -> IO ()
>validate h db = do
> hPutStr h "username: "
> name <- liftM (filter (/='\r')) $ hGetLine h
> hPutStr h "password: "
> pass <- liftM (filter (/='\r')) $ hGetLine h
> (found,pass') <- atomically $ loginLookup name db
> if found && (pass'==pass)
> then hPutStrLn h "You can log in!"
> else hPutStrLn h "Not valid."
> loginServer h db
>create :: Handle -> DB -> IO ()
>create h db = do
> hPutStr h "username: "
> name <- liftM (filter (/='\r')) $ hGetLine h
> (found,_) <- atomically $ loginLookup name db
> if found
> then hPutStrLn h "Name already in use!"
> else do
> hPutStr h "Choose a password: "
> pass <- liftM (filter (/='\r')) $ hGetLine h
> atomically $ pushDB name pass db
> hPutStrLn h "Account created"
> loginServer h db
>loginLookup :: String -> DB -> STM (Bool,String)
>loginLookup name db = do
> db' <- readTVar db
> case lookup name db' of
> Nothing -> return (False,"")
> Just p -> return (True,p)
>pushDB :: String -> String -> DB -> STM ()
>pushDB name pass db = do
> db' <- readTVar db
> writeTVar db ((name,pass):db')

Now this isn't the cleanest code, and I'm worried I may have missed some edge cases that can make it fail, but for the most part I think this is a pretty decent example of shared transactional memory combined with the Network library. The main point is that STM allows us to mostly ignore issues of how to keep everything synched together.


Creighton Hogg said...

Okay I'm stumped. I don't know why it looks fine on the blog itself but all the heads of the do syntax arrows are gone on planet haskell. Blergh.

Andreas Krey said...

The <- are probably gone the way of an minimalistic HTML tag filter...

You are also missing the import magic needed to make the code compile (which took me (newbie at haskell) a bit to figure out; Control.Concurrent, Network (and not Network.Socket), Control.Monad, System.IO). Now I need to understand the stranger stuff. -- $ turned out to be easy.

Creighton Hogg said...

Ah, I figured the imports would look annoying so I took them out when copied from my .lhs file. I guess I'll put them in future posts, my apologies.

Antoine said...

If you want the look of my blog I can email you the template. I edited it purpose for showing code without cutting off the edges.

You'll still need to do most of the entry in the "view html" side of the post editor - every time you switch from "view html" to the pretty composer, it'll screw up your linebreaks even if they're in pre tags.

Anonymous said...

I'm concerned that in ``create'' between checking that a name is not used, and creating the account, someone might sneak in and create an account with that name. Then you would end up with two accounts with the same name.

Unknown said...

Nice post, thanks.
Just a little nitpick - your example would be a bit nicer, if you give "liftM (filter (/='\r')) $ hGetLine h " a name.

Creighton Hogg said...

Anonymous: I knew there was probably something I had overlooked. Yes, you're right that could totally happen. Since you can't do IO within a transaction I'd have to collect the password before doing the check, I guess.

Anonymous said...

Do you find me hot ?

You can see me here

[url=]My Profile[/url]

Anonymous said...


[b]Xrumer SEO Professionals

As Xrumer experts, we from been using [url=]Xrumer[/url] quest of a sustained immediately now and know how to harness the enormous power of Xrumer and turn it into a Banknotes machine.

We also provender the cheapest prices on the market. Numberless competitors devise charge 2x or even 3x and a end of the term 5x what we debt you. But we believe in providing prominent service at a tearful affordable rate. The large incidental of purchasing Xrumer blasts is because it is a cheaper surrogate to buying Xrumer. So we aim to abide by that bit in rebuke and outfit you with the cheapest rate possible.

Not solitary do we take the most successfully prices but our turnaround in the good old days b simultaneously after your Xrumer posting is super fast. We drive pull someone's leg your posting done to come you certain it.

We also cater you with a sated log of loaded posts on manifold forums. So that you can notice for yourself the power of Xrumer and how we be struck by harnessed it to gain your site.[/b]

[b]Search Engine Optimization

Using Xrumer you can trust to apprehend thousands upon thousands of backlinks over the extent of your site. Scads of the forums that your Place you force be posted on oblige exalted PageRank. Having your association on these sites can categorically serve found up some top quality help links and really aid your Alexa Rating and Google PageRank rating owing to the roof.

This is making your site more and more popular. And with this increase in celebrity as familiarly as PageRank you can expect to witness your site in effect rank expensive in those Search Locomotive Results.

The amount of conveyance that can be obtained by harnessing the power of Xrumer is enormous. You are publishing your plat to tens of thousands of forums. With our higher packages you may still be publishing your position to HUNDREDS of THOUSANDS of forums. Visualize 1 collection on a in demand forum last will and testament by cotton on to a leave 1000 or so views, with communicate 100 of those people visiting your site. These days devise tens of thousands of posts on fashionable forums all getting 1000 views each. Your shipping will go through the roof.

These are all targeted visitors that are interested or exotic nearly your site. Assume how divers sales or leads you can achieve with this great number of targeted visitors. You are literally stumbling upon a goldmine ready to be picked and profited from.

Retain, Transport is Money.


Anonymous said...

Dont Bother With Laggin Downloads Using NZB Downloads You Can Rapidly Find Movies, PC Games, Music, Software and Download Them at Accelerated Rates


Anonymous said...

Reside Our Adverse Prices at, The Unequalled [b][url=]Online Chemist's seek [/url][/b] To [url=]Buy Viagra[/url] Online ! You Can also Branchlet Mammoth Deals When You [url=]Buy Cialis[/url] and When You You [url=]Buy Levitra[/url] Online. We Also Beadroll a Bountiful Generic [url=]Phentermine[/url] Repayment for the treatment of the on pungency of Your Regimen ! We Huckster Merchandise earmark colossal submit [url=]Viagra[/url] and Also [url=]Generic Viagra[/url] !

Anonymous said...

Hi Guys,Just registered here and looking to have a great time. I am looking for the best cash gifting program out there in the internet. Can you guide me?

Below are some sites that I found and I am not sure how much they are going to help me.
[url=]cash gifting[/url]
[url=]join cash gifting[/url]
[url=]best cash gifting program[/url]

Anonymous said...

Hi all,
I found very good source of finding dofollow high parerank backlinks. Even from real PR10.
I cant imagine value of a real pr10.

I would like to share with you all about how i succeded to rank on 1st page on google.

Anonymous said...

You could easily be making money online in the hush-hush world of [URL=]blackhat money[/URL], You are far from alone if you haven’t heard of it before. Blackhat marketing uses not-so-popular or little-understood methods to build an income online.

Anonymous said...

Not sure where to post this but I wanted to ask if anyone has heard of National Clicks?

Can someone help me find it?

Overheard some co-workers talking about it all week but didn't have time to ask so I thought I would post it here to see if someone could help me out.

Seems to be getting alot of buzz right now.


retirement homes in costa rica said...

thanks for the info, is very good!
retirement homes in costa rica

Imitrex said...

Costa Rica is an excellent country to invest in real estate its economy is very stable, being a peaceful country and have their exuberant nature makes it much more attractive costa rica best investment in your life!!

Steve said...

Hello .. firstly I would like to send greetings to all readers. After this, I recognize the content so interesting about this article. For me personally I liked all the information. I would like to know of cases like this more often. In my personal experience I might mention a book called Generic Viagra in this book that I mentioned have very interesting topics, and also you have much to do with the main theme of this article.

eco vacation costa rica said...

Hey buddy very interesting article about A couple of silly examples I would like to have any update about it, thanks for sharing!!!

Firesales Costa Rica said...

Hello.. Firstly I would like to send greetings to all readers. After this, I recognize the content so interesting about this article. For me personally I liked all the information. I would like to know of cases like this more often. In my personal experience I might mention a book called Firesales Costa Rica in this book that I mentioned have very interesting topics, and also you have much to do with the main theme of this article.

Louis Vuitton Damier Speedy said...

Don’t drink anything for at least 15 minutes before and 30 minutes after your meals. That’s right, no drinking during the meal either. You’d be amazed at how much more you taste your food when you’re not immediately washing it all down. As a result, you’re likely to enjoy what you eat more yet consume smaller quantities.
louis vuitton handbags
louis vuitton bags
louis vuitton
louis vuitton purse
louis vuitton

Super Bowl Commercials 2012 said...

Thanks for the post. I liked it. Keep going I follow you.
Super Bowl Commercials 2012| Money Talks|