WebSocketã§ãã³ãã³ãªã¢ã³ã³ã¿ãããªã®ãä½ã£ã¦ã¿ã
ã¯ããã«
ãã®è¨äºã¯ãJavaScript Advent Calendar 2011 (Node.js/WebSocketsã³ã¼ã¹)ã®20æ¥ç®ã®è¨äºã§ããé£ã³å
¥ãåå ã§ãã
注ï¼éçºé度éè¦ã§æ¸ããã³ã¼ããªã®ã§ã綺éºãçç¡ã§ãï¼ï¼ ãã¿ã¾ããï¼ï¼
ãã®ä¸åå¹´åã®ã³ã¼ããªã®ã§è²ã
ã¨ã¢ã¬ã§ãï¼ï¼
æ¦è¦
ãã³ãã³ãªã¢ã³ã³ãçãã使ã£ã¦ã¾ããï¼åã¯ä½¿ã£ã¦ãªãã§ããã¨ãããã¹ãããªã®ã§ãµãã¼ãããã¦ãã¾ããã
使ããªããªãèªåã§ä½ããï¼ï¼ã¨ããã®ãä»åã®ç®çã§ãã
ã ãã¶@ajalaboxããã®ãGoogle ChromeãWebSocketã§å¶å¾¡ãããã¨ãã¶ã£ã¦ããæ°ããã¾ãããã¿ã¾ãã…
ä»çµã¿
2ã¤ã®ç«¯æ«ãåãæã«æ¥ç¶ãã¾ãã
çæ¹ãã¬ã·ã¼ããããçæ¹ãã³ã³ããã¼ã©ãé¸ã³ã¾ãã
ã³ã³ããã¼ã©ãä½ãæ示ãåºããæãWebSocketã«ãã®æ示ãæµãããµã¼ããéãæ以å¤ã®æ¥ç¶ãã¦ãã端æ«ã«éãã¾ãã
ã¬ã·ã¼ãã¯ãã®æ示ã解èªãããã³ãã³åç»ãå¶å¾¡ãã¾ãã
ãµã¼ãå´ã®ã³ã¼ã1ã¤ãã¯ã©ã¤ã¢ã³ãå´ã®ã³ã¼ã1ã¤ãã¬ã·ã¼ãç¨ã®æ¡å¼µæ©è½1ã¤ãä½ãã¾ãã
å®éã«ä½ã£ã¦ã¿ã
node.jsãã¤ã³ã¹ãã¼ã«ãã¾ããããåã¯0.4.9ã使ãã¾ããã
次ã«npmãã¤ã³ã¹ãã¼ã«ãã¦ãexpressã¨socket.ioãã¤ã³ã¹ãã¼ã«ãã¾ããããsocket.ioã¯0.6.17ã使ãã¾ããã
ããããæ¬ä½ã§ãã
ã¾ãã¯ãæä½ç»é¢ãä½ãã¾ãã
æä½ç»é¢ã¯ä¸ã®ãããªæãã«ãã¾ããã
第ä¸å½¢æ
æçµå½¢æ
ï¼ã³ã³ããã¼ã©
æçµå½¢æ
ï¼ã¬ã·ã¼ã
index.html(ä¸é¨)
index.html(ãã«)
æä½ç»é¢ãå®æãã¾ããã
ã次ã«ãã©ã¦ã¶ã®å¶å¾¡ãè¡ãã¾ãããããã©ã®ããã«å¶å¾¡ãã¾ãããï¼
ãã åã«ã¦ã¤ã³ãã¦ãéãã ããªãç°¡åãªã®ã§ãããä»åã¯æ¢ã«éãã¦ããã¿ãã«ã¹ã¯ãªããã注å
¥ããªããã°ãªãã¾ããã
ããã§ãç°¡åãªChromeæ¡å¼µãä½ãã¾ããã
ã½ã¼ã¹ã³ã¼ãã¯ä»¥ä¸ã®1ã¤ã ãã§ãã
background.html(ä¸é¨)
background.html(ãã«)
ãã®ã³ã¼ããä½ããã¦ãããã®åã«ãã¬ã·ã¼ãã®ä»æ§ã«ã¤ãã¦ã
ã¬ã·ã¼ããä½ããã½ã±ããããåä¿¡ããæãURLã®hashã«ãåä¿¡ãããã®ããã£ã¤ãã¾ãã
ä¾ï¼
http://localhost:12000/#receive
↓ { type: 'aaa' } ã¨ããæ å ±ãåä¿¡
URLã http://localhost:12000/#receive/{type:'aaa'} ã¨ãªã£ãã®ã¡ãhttp://localhost:12000/#receive ã«æ»ã
ãªãJSONã«ãããã¨ãããã¯åå¹´åã®åã«èãã¦ãã ããã
ã¨ã«ãããæ
å ±ãåä¿¡ããã¨ããã®ããã«hashãå¤åãã¾ãã
ããã§ãå
ç¨ä½ã£ãæ¡å¼µæ©è½ã®åºçªã§ãã
ã¿ããæ´æ°ãããã¨ãã«ãç»é²ããã³ã¼ã«ããã¯é¢æ°ãå¼ã³åºããã¾ãã
ããã¯ãhashãå¤ãã£ãã ãã§ãå¼ã³åºããã¾ããããã§åä¿¡ããå½ä»¤ãåå¾ãã¾ãã
ãããããã¨ã¯ããã³ãã³åç»ãéãã¦ããã¿ããæ¢ãã¦ãåçãããä¸æåæ¢ãããããã³ã¼ãã注å
¥ããã ãã§ãã
ãµã¼ãå´ã®ã³ã¼ãã¯ä»¥ä¸ã®ã¨ããã§ãã
server.js
ãã åã«éããã¦ãããã®ãéãè¿ãã ãã§ãã
åããã¦ã¿ã
å®éã«åããã¦ã¿ã¾ãããã
node server.js
ãã¼åãã¦ã¾ãåãã¦ã¾ãï¼ï¼
éãªå®è£
ã§ããããã¡ãã¨iPod touchãããæä½ã§ãã¦ã¾ãï¼ï¼
ãã³ãã¯åç»ã§ãæ®ãããã£ãã®ã§ãããæé ãªä¸èããªãã£ãã®ã§æ念ãã¾ããã
ãããã«
Advent Calendaråãã®è¨äºã§ã¯ãªãã£ãããããã¾ãã… åçã
Chromeæ¡å¼µã®æãå°ãåä»ã§ããããWebSocketèªä½ã¯é常ã«ç°¡åã«æ±ããã¨ãåºæ¥ã¾ããã
ãã®è¨äºãè¦ã¦ãã²ã¨ãã§ãå¤ãã®æ¹ãWebSocketãnode.jsã«èå³ãæã£ã¦ããã ããã°ã¨æãã¾ãã