ãªãã¨ãªã12æ¥ã空ãã¦ããã®ã§æ¸ãã¦ã¿ã¾ã*1ã
ãã®ã¨ã³ããªã¯ ãã¼ãã§ã¯ãRuby Advent Calendar ã®12æ¥ç®ã®ã¨ã³ããªã§ãã åã®æ¥ã®ã¨ã³ããªã¯ã¤ãªãªãã http://iori-o.github.io/blog/2013/12/11/perfect-ruby-2013-12-11/ ã§ããã
ãã¼ãã§ã¯ãRuby (PERFECT SERIES 6)
- ä½è : Rubyãµãã¼ã¿ã¼ãº,ããããã¾ãã®ã,寺ç°ç太é,ä¸æçé,è¿è¤å®æºæ,æ©ç«åå®,é¢å£äº®ä¸
- åºç社/ã¡ã¼ã«ã¼: æè¡è©è«ç¤¾
- çºå£²æ¥: 2013/08/10
- ã¡ãã£ã¢: 大åæ¬
- ãã®ååãå«ãããã° (10件) ãè¦ã
ãã¼ãã§ã¯ãRubyããæ³£ãæ³£ãåã£ãæ¨æºæ·»ä»ã©ã¤ãã©ãª
ãã¼ã¸æ°ã®é½åã§æ³£ãæ³£ãåããã¨ã«ãªã£ã¦ãã¾ã£ãé¨åã¨ããã®ãå¤å°ãªãã¨ãããã¾ãããã®ä»ã«ãããè¼ããã»ããè¯ããã ãã©ãã¼ã¸æ°ã(ryã¨ããã®ãããã¾ãã
ããã§åã£ã¦ãã¾ã£ããã©ãæ¬å½ã¯ããã¨è¯ãã£ããªã¨ããã®ãç´¹ä»ãã¾ãã
IO#select
ããã¯ããããselect(2)ãæä¾ãã¦ããã¾ããselect(2)ã£ã¦ä½ã¹ã«ã£ã¦ããã¨man select 2
ããã°è¯ããããªãã£ã¦æããªãã§ããã©ããã¶ãIOãªãã¸ã§ã¯ãï¼ãã£ã¨è¨ãã¨ãã¡ã¤ã«ãã£ã¹ã¯ãªãã¿ããªï¼ãå¾
ã¡åãã¦ãèªã¿åãæºåãã§ãããªãã¸ã§ã¯ããè¿ãã£ã¦æãã§ãããã
ã§ï¼ã£ã¦ãã
ä¾ãã°ãTCPServerã®ãµã³ãã«ã¨ãã§ä½¿ããã¦ãã®ã§ãããããäºä¾ãè¦ãã¨è¯ãã¨æãã
ããã®ãµã³ãã«ã½ã¼ã¹ã§TCPServerã使ã£ãã¨ã³ã¼ãµã¼ããããã
require "socket" gs = TCPServer.open(0) socks = [gs] addr = gs.addr addr.shift printf("server is on %s\n", addr.join(":")) while true nsock = select(socks) next if nsock == nil for s in nsock[0] if s == gs socks.push(s.accept) print(s, " is accepted\n") else if s.eof? print(s, " is gone\n") s.close socks.delete(s) else str = s.gets s.write(str) end end end end
ããã® nsock = select(socks)
ã£ã¦ã¨ããã§ä½¿ããã¦ãããå®ã¯Kernel#selectã¯IO#selectã¨åããªã®ã§ãåã«selectã¨ãæ¸ããã®ã ã£ãã
ããã§ãã£ã¦ãã®ã¯TCPServerãopenãã¦éããsocketãIO#selectã§å¾
ã£ã¦ãå
¥åããã£ãããã®æååããã®ã¾ã¾è¿å´ããï¼s.write(str)
ã®ã¨ããï¼ã¨ããã®ããã£ã¦ãããã§ããã
ã¡ãªã¿ã«ãä¸è¨ã®ã¹ã¯ãªãããå®è¡ããã¨ãããªæãã§åºåãããã
% ruby sample.rb server is on 51450:0.0.0.0:0.0.0.0
ããããããå¥ã®ã¿ã¼ããã«ããããããã« telnet localhost 51450*2 ãã¦ãä½ãæååãæã£ã¦ã¿ãã¨åä½ã確èªã§ãã¾ãã
ãã®IO#selectã¨ããã®ã¯é åã®é åã§è¿ã£ã¦ããã®ã§ãªããªããã¼ã¿æ§é ãææ¡ããã®ã大å¤ãªã®ã§ãããããããä½ã¬ã¤ã¤ã¼ã£ã½ããã®ã®åä½ã調ã¹ãã®ããªããªã楽ããã§ãããã
次ã®ã¢ããã³ã¿ã¼ã¯ id:akiinyo ããã§ããæ¬æ¸ã®ã¬ãã¥ã¼ã§ãå©ãã¦é ãã¾ããâ¦â¦!!