ÔËÓÃÒì²½ÊäÈëÊä³öÁ÷±àдSocket½ø³ÌͨÐÅ - ±à³ÌÈëÃÅÍø
¹¤×÷·½Ê½¡£ÓëÒÔÇ°°æ±¾µÄAPIÏà ±È½Ï£¬ServerSocketChannel¾ÍÏ൱ÓÚServerSocket(ServerSocketChannel·â×° ÁËServerSocket),¶øSocketChannel¾ÍÏ൱ÓÚSocket£¨SocketChannel·â×°ÁË Socket£©¡£µ±Í¨µÀ¹¤×÷ÔÚͬ²½·½Ê½Ê±£¬±à³Ì·½·¨ÓëÒÔÇ°µÄ»ù±¾ÏàËÆ£¬ÕâÀïÖ÷Òª½é ÉÜÒì²½¹¤×÷·½Ê½¡£
ËùνÒì²½ÊäÈëÊä³ö»úÖÆ£¬ÊÇÖ¸ÔÚ½øÐÐÊäÈëÊä³ö´¦Àíʱ £¬²»±ØµÈµ½ÊäÈëÊä³ö´¦ÀíÍê±Ï²Å·µ»Ø¡£ËùÒÔÒì²½µÄͬÒåÓïÊÇ·Ç×èÈû£¨None Blocking£©¡£ÔÚ·þÎñÆ÷¶Ë£¬ServerSocketChannelͨ¹ý¾²Ì¬º¯Êýopen()·µ»ØÒ»¸ö ʵÀýserverChl¡£È»ºó¸ÃͨµÀµ÷ÓÃserverChl.socket().bind()°ó¶¨µ½·þÎñÆ÷ij¶Ë ¿Ú£¬²¢µ÷ÓÃregister£¨Selector sel, SelectionKey.OP_ACCEPT£©×¢²á OP_ACCEPTʼþµ½Ò»¸öÑ¡ÔñÆ÷ÖУ¨ServerSocketChannelÖ»¿ÉÒÔ×¢²áOP_ACCEPTÊ ¼þ£©¡£µ±Óпͻ§ÇëÇóÁ¬½Óʱ£¬Ñ¡ÔñÆ÷¾Í»á֪ͨ¸ÃͨµÀÓпͻ§Á¬½ÓÇëÇ󣬾ͿÉÒÔ½ø ÐÐÏàÓ¦µÄÊäÈëÊä³ö¿ØÖÆÁË£»ÔÚ¿Í»§¶Ë£¬clientChlʵÀý×¢²á×Ô¼º¸ÐÐËȤµÄʼþºó £¨¿ÉÒÔÊÇOP_CONNECT,OP_READ,OP_WRITEµÄ×éºÏ£©£¬µ÷ÓÃclientChl.connect (InetSocketAddress )Á¬½Ó·þÎñÆ÷È»ºó½øÐÐÏàÓ¦´¦Àí¡£×¢Ò⣬ÕâÀïµÄÁ¬½ÓÊÇÒì²½ µÄ£¬¼´»áÁ¢¼´·µ»Ø¶ø¼ÌÐøÖ´ÐкóÃæµÄ´úÂë¡£ ÔËÓÃÒì²½ÊäÈëÊä³öÁ÷±àдSocket½ø³ÌͨÐÅ(2)ʱ¼ä:2010-12-14 ÑѡÔñÆ÷ºÍÑ¡Ôñ¼ü½éÉÜ£º Ñ¡ÔñÆ÷£¨Selector£©µÄ×÷ÓÃÊÇ£º½«Í¨µÀ¸ÐÐËȤµÄʼþ·ÅÈë¶ÓÁÐÖУ¬¶ø²» ÊÇÂíÉÏÌá½»¸øÓ¦ÓóÌÐò£¬µÈÒÑ×¢²áµÄͨµÀ×Ô¼ºÀ´ÇëÇó´¦ÀíÕâЩʼþ¡£»»¾ä»°Ëµ£¬ ¾ÍÊÇÑ¡ÔñÆ÷½«»áËæʱ±¨¸æÒѾ׼±¸ºÃÁ˵ÄͨµÀ£¬¶øÇÒÊÇ°´ÕÕÏȽøÏȳöµÄ˳Ðò¡£ÄÇ Ã´£¬Ñ¡ÔñÆ÷ÊÇͨ¹ýʲôÀ´±¨¸æµÄÄØ£¿Ñ¡Ôñ¼ü(SelectionKey)¡£Ñ¡Ôñ¼üµÄ×÷ÓþÍÊÇ ±íÃ÷ÄĸöͨµÀÒѾ×öºÃÁË×¼±¸£¬×¼±¸¸Éʲô¡£ÄãÒ²ÐíÂíÉÏ»áÏëµ½£¬ÄÇÒ»¶¨ÊÇÒÑ×¢ ²áµÄͨµÀ¸ÐÐËȤµÄʼþ¡£²»´í£¬ÀýÈç¶ÔÓÚ·þÎñÆ÷¶ËserverChlÀ´Ëµ£¬¿ÉÒÔµ÷Óà key.isAcceptable()À´Í¨ÖªserverChlÓпͻ§¶ËÁ¬½ÓÇëÇó¡£ÏàÓ¦µÄº¯Êý»¹ÓУº SelectionKey.isReadable(),SelectionKey.isWritable()¡£Ò»°ãµÄ£¬ÔÚÒ»¸öÑ »·ÖÐÂÖѯ¸ÐÐËȤµÄʼþ£¨¾ßÌå¿É²ÎÕÕÏÂÃæµÄ´úÂ룩¡£Èç¹ûÑ¡ÔñÆ÷ÖÐÉÐÎÞͨµÀÒÑ×¢ ²áʼþ·¢Éú£¬µ÷ÓÃSelector.select()½«×èÈû£¬Ö±µ½ÓÐʼþ·¢ÉúΪֹ¡£ÁíÍ⣬¿É ÒÔµ÷ÓÃselectNow()»òÕßselect(long timeout)¡£Ç°ÕßÁ¢¼´·µ»Ø£¬Ã»ÓÐʼþʱ·µ »Ø0Öµ£»ºóÕߵȴýtimeoutʱ¼äºó·µ»Ø¡£Ò»¸öÑ¡ÔñÆ÷×î¶à¿ÉÒÔͬʱ±»63¸öͨµÀÒ»Æð ×¢²áʹÓᣠӦÓÃʵÀý£º ÏÂÃæÊÇÓÃÒì²½ÊäÈëÊä³ö»úÖÆʵÏֵĿͻ§/ ·þÎñÆ÷ʵÀý³ÌÐòÇåµ¥£¨ÏÞÓÚƪ·ù£¬Ö»¸ø³öÁË·þÎñÆ÷¶Ë ʵÏÖ£¬¶ÁÕß¿ÉÒÔ²ÎÕÕ×ÅʵÏÖ¿Í»§¶Ë´úÂ룩£º ³ÌÐòÀàͼ ³ÌÐòÇåµ¥1
|
ÁèÖڿƼ¼×¨ÒµÌṩ·þÎñÆ÷×âÓᢷþÎñÆ÷Íйܡ¢ÆóÒµÓʾ֡¢ÐéÄâÖ÷»úµÈ·þÎñ£¬¹«Ë¾ÍøÕ¾£ºhttp://www.lingzhong.cn ΪÁ˸ø¹ã´ó¿Í»§Á˽â¸ü¶àµÄ¼¼ÊõÐÅÏ¢£¬±¾¼¼ÊõÎÄÕÂÊÕ¼¯À´Ô´ÓÚÍøÂç,ÁèÖڿƼ¼×ðÖØÎÄÕÂ×÷ÕߵİæȨ£¬Èç¹ûÓÐÉæ¼°ÄãµÄ°æȨÓбØҪɾ³ýÄãµÄÎÄÕ£¬ÇëºÍÎÒÃÇÁªÏµ¡£ÒÔÉÏÐÅÏ¢ÓëÎÄÕÂÕýÎÄÊDz»¿É·Ö¸îµÄÒ»²¿·Ö,Èç¹ûÄúҪתÔر¾ÎÄÕÂ,Çë±£ÁôÒÔÉÏÐÅÏ¢£¬Ð»Ð»! |
-
HTTP/1.1 401 Access Denied