그래서 이전 코드에서 세션핸들러 함수들이 Socket 을 받던것을 Handle 을 받도록 수정해봤다. 그리고 핸들(소켓) 을 닫는 책임을 세션핸들러 쪽으로 옮겨버렸다... 세션함수 작성시 클로즈를 잊지말고 해야 하는 부담이 있긴 하지만 이게 좀더 유연할거 같다.
이건 서버쪽 소스
이건 클라이언트쪽 소스펼쳐두기..
펼쳐두기..
헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤헤
이건 클라이언트쪽 소스펼쳐두기..
-- haskell 에서 입출력을 하려면 소켓보다는 핸들이 좀더 나은것 같아서
-- 소켓 기반이었던 것을 핸들 기반으로 바꿨다. 소켓인 경우 소켓만으로
-- peer 를 알수 있지만 핸들은 좀더 추상화 된 놈이라.. 핸들을 다루는
-- 놈한테 peer 정보까지 인자로 넘기도록 했다.
import Prelude hiding (log)
import Network.Socket
import Control.Monad(liftM,forever)
import Control.Exception(finally)
import Control.Concurrent(forkIO)
import System.IO
serveTcp port f = do
s <- socket AF_INET Stream defaultProtocol
bindSocket s (SockAddrInet port iNADDR_ANY)
listen s maxListenQueue
forever $ do
(child,from) <- accept s
h <- socketToHandle child ReadWriteMode
hSetBuffering h (BlockBuffering Nothing)
forkIO $ f h from
-- 사용하지는 않지만 핸들 외에 SockAddr 도 받았다. 어쨌거나 peer 정보를
-- 알수 있다는거.
log :: Handle -> SockAddr -> IO ()
log h from = (forever $ hGetLine h >>= print) `finally` hClose h
main = withSocketsDo $ serveTcp 1818 log
펼쳐두기..
import Network.Socket
import Control.Monad(liftM,forever)
import Control.Exception(finally)
import Control.Concurrent(threadDelay)
import System.IO
withTcp :: (String,PortNumber) -> (Handle->IO a) -> IO a
withTcp (ip,port) f = do
a <- liftM (SockAddrInet port) (inet_addr ip)
s <- socket AF_INET Stream defaultProtocol
connect s a
h <- socketToHandle s ReadWriteMode -- 소켓을 직접 다루는건 좀 빡시네. 핸들로 바꿔서 움직이는게 좀더 나은 방법인갑다
hSetBuffering h (BlockBuffering Nothing) -- 버퍼링 모드.. 일단 블럭모드로
f h -- 핸들(소켓) 을 닫는것을 f 의 책임으로 넘겼다.
withServer = withTcp ("127.0.0.1",1818)
shootPackets :: Handle -> IO ()
shootPackets h = forever (shoot >> sleep) `finally` finalize
where shoot = hPutStrLn h "Hello" >> hFlush h
sleep = threadDelay 1000000
finalize = hClose h
main = withSocketsDo $ withServer shootPackets
이건 클라이언트 소스펼쳐두기..
import Prelude hiding (log)
import Network.Socket
import Control.Monad(liftM,forever)
import Control.Exception(finally)
import Control.Concurrent(forkIO)
-- withTcp 의 서버쪽 버전. 에러처리가 없으니 좀 허한데 테스트엔 문제
-- 없다.
serveTcp port f = do
s <- socket AF_INET Stream defaultProtocol
bindSocket s (SockAddrInet port iNADDR_ANY)
listen s maxListenQueue
forever $ do
(child,from) <- accept s
forkIO $ f child `finally` sClose child
-- 걍 화면에 출력만 하자.
log :: Socket -> IO ()
log sock = forever $ do
buf <- recv sock 1024
print (sock,buf)
main = withSocketsDo $ serveTcp 1818 log
-- 한가지 적어두자면, 원래 serveTcp 안에 forkIO 를 두지 않고
-- serveTcpMulti 란 함수를 만들어서 (forkIO . f) 를 serveTcp 로
-- 넘겨주는 식으로 만들었었다. 이런식으로 짜게 되면 serveTcp 가
-- 쓰레드방식에 대해서 독립적으로 돌아가니까.. 그런데 마지막에 child
-- 소켓을 닫아주는 처리가 좀 애매해지더라. forkIO 를 띄운 직후에
-- sClose 해버리면 자식쓰레드쪽에선 소켓이 닫혀버리니까..
--
-- 이걸 어떻게 이쁘게 해보려고 좀 고민해봤는데 좋은 방법이 안떠오르네.
-- 그런데 써둔걸 보니 나중에 읽어보면 뭔소린지 모르겠군..
으음... 이건 패킷이 너무 단순해서 별 의미는 없지만 위에 withTcp 나 serveTcp 는 자주 쓰일 함수들이라 적어둔다. 다음에는 현재 Socket 기반인것을 Handle 기반으로바꾸고.. 바이너리패킷을 쏘는걸 한번 만들어보고.. 그담엔 서로 주고받는걸 만들어보자...펼쳐두기..
import Network.Socket
import Control.Monad(liftM,forever)
import Control.Exception(finally)
import Control.Concurrent(threadDelay)
-- tcp 연결해서 f 에 넘기고 그 결과를 리턴. 흔한 with 류 함수
withTcp :: (String,PortNumber) -> (Socket->IO a) -> IO a
withTcp (ip,port) f = do
a <- liftM (SockAddrInet port) (inet_addr ip)
s <- socket AF_INET Stream defaultProtocol
connect s a
f s `finally` sClose s
-- 테스트서버는 위치가 고정이니 적당히 박았다.
withServer :: (Socket -> IO a) -> IO a
withServer = withTcp ("127.0.0.1",1818)
-- 패킷 쏘고 쉬고...
shootPackets :: Socket -> IO ()
shootPackets sock =
forever $ do
send sock "Hello"
threadDelay 1000000
main = withSocketsDo $ withServer shootPackets
-- http://projecteuler.net/index.php?section=problems&id=22
import Data.List(sort)
import Data.Char(ord)
-- 으험.. 스플릿 함수가 안보이네. 직접 만들어봤는데 좀 추해보인다.
split :: Char -> String -> [String]
split c s = split' [] s
where split' acc [] = acc
split' acc s = let (tok, remains) = break (==c) s
in split' (tok:acc) (safeTail remains)
safeTail [] = []
safeTail x = tail x
-- 문자열들을 받아서 , 로 스플릿 하고 앞뒤에서 한글자씩 잘라냈다.
-- 따옴표 제거
names s = map (tail . init) $ split ',' s
nth x = (ord x) - (ord 'A') + 1 -- 'A' 에서 몇번째 문자냐
scoreName = sum . map nth -- 이름의 점수
scoreIndexedName (name,index) = (scoreName name) * index -- 점수에 인덱스 곱
solve input =
let splitted = names input -- 쪼개고
sorted = sort splitted -- 정렬하고
indexed = zip sorted [1..] -- 인덱스붙여서
scores = map scoreIndexedName indexed -- 점수내고
in sum scores -- 합
main = do
input <- readFile "/tmp/h/names.txt"
print $ solve input
A Really Quick Guide to Magic Inscriptions..
There are a number of special things you can inscribe (with the { command) on your equipment and inventory to make playing Angband more convenient.
n is a number from 0-9
c is a command from the underlying command set. (Almost, but not completely, like the orginial command set, which uses some keymaps so you don't need to know that ; is the walk command, and such. See the help file command.txt for these.)
!c - Ask for confirmation when you select this item to use with command c.
!* - Ask for confirmation when you select this item to use with any command.
@n - When you type n at a what object? prompt for any command, use this item. (If more than one item has this inscription, it uses the first one.)
@cn - As above, but only when selecting objects for command c.
For both of these, if the first matching inscription in your inventory is an illegal choice, it will stop there, not go on to a legal one.
These two are especially useful in macros, since they allow you to make a macro to use rod 2, for instance, and not have to worry about what inventory slot it is currently in. Or, for making macros of spells, it causes the macro to fail if all your copies of the appropriate book are destroyed, moving a different book into the same slot.
^c - While this item is equipped, ask for confirmation of command c.
=g - Pick this item up when you step on it.
펼쳐두기..
by Conal Elliott Nov 18, 2008; 12:56am