程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> URL學習筆記,印象筆記url

URL學習筆記,印象筆記url

編輯:JAVA綜合教程

URL學習筆記,印象筆記url


不多說,先上代碼,代碼的注釋寫的已經挺詳細的了

 1 //URL:統一資源定位符,一個URL的對象,對應著互聯網上的一個資源。
 2 //我們可以通過URL的對象調用其相應的方法,將此資源讀取(即所謂的“下載”)
 3 public class TestURL {
 4     //看URL下有哪些常用的方法
 5     @Test
 6     public void Testurl() throws MalformedURLException{
 7         //1.創建一個URL的對象
 8         //參數部分可以傳入一個網址的絕對路徑,這裡我傳人的是我寫的一篇博客的地址
 9         URL url = new URL("http://www.cnblogs.com/gode/p/5812013.html");
10         
11         //獲取該URL的協議名
12         System.out.println(url.getProtocol());//http
13         //獲取該URL的主機名
14         System.out.println(url.getHost());//www.cnblogs.com
15         //獲取該URL的端口號
16         System.out.println(url.getPort());//-1
17         //獲取該URL的文件路徑
18         System.out.println(url.getPath());//  /gode/p/5812013.html
19         //獲取該URL的文件名
20         System.out.println(url.getFile());//  /gode/p/5812013.html
21         //獲取該URL在文件中的相對位置
22         System.out.println(url.getRef());//null
23         //獲取該URL的查詢名
24         System.out.println(url.getQuery());//null
25     }


首先先了解了URL的一些常用的方法,現在我嘗試利用網址讀入內容到控制台打印輸出

很好奇會打印出什麼東西呢

 1     //如何將服務端的資源讀取進來
 2     @Test
 3     public void Testurl1() throws Exception{
 4         //1.創建一個URL的對象
 5         //參數部分可以傳入一個網址的絕對路徑,這裡我傳人的是我寫的一篇博客的地址
 6         URL url = new URL("http://www.cnblogs.com/gode/p/5812013.html");
 7         
 8         //2.URL讀入的方法是openStream
 9         InputStream is = url.openStream();
10         
11         //3.打印到控制台上試試
12         byte[] b = new byte[1024];
13         int length;
14         while((length = is.read(b)) != -1){
15             String str = new String(b,0,length);
16             System.out.print(str);//這裡輸出的是頁面布局的HTML代碼,對應的漢字還有些是亂碼
17         }
18     }

下面就是打印出來的東西

  1 <!DOCTYPE html>
  2 <html lang="zh-cn">
  3 <head>
  4 <meta charset="utf-8"/>
  5 <title>浣跨敤UDP杩涜鏁版嵁鍙戦?佺殑瀹炰緥涓? - Hello.World! - 鍗氬鍥?</title>
  6 <link type="text/css" rel="stylesheet" href="/bundles/blog-common.css?v=Ugwf7ssw_T-Y4bsdVDPHPhPR9NEESRNHOF-E8IRqEJk1"/>
  7 <link id="MainCss" type="text/css" rel="stylesheet" href="/skins/CodingLife/bundle-CodingLife.css?v=dE43LeVMdRWr6dflRs5MpsAmgg8oyLrU-UvBlmYDLvg1"/>
  8 <link title="RSS" type="application/rss+xml" rel="alternate" href="http://www.cnblogs.com/gode/rss"/>
  9 <link title="RSD" type="application/rsd+xml" rel="EditURI" href="http://www.cnblogs.com/gode/rsd.xml"/>
 10 <link type="application/wlwmanifest+xml" rel="wlwmanifest" href="http://www.cnblogs.com/gode/wlwmanifest.xml"/>
 11 <script src="//common.cnblogs.com/script/jquery.js" type="text/javascript"></script>  
 12 <script type="text/javascript">var currentBlogApp = 'gode', cb_enable_mathjax=false;var isLogined=false;</script>
 13 <script src="/bundles/blog-common.js?v=Q7JqGMCRFJwGRojUTJLkQ6nIu4kUBVwm5mErn4um_MM1" type="text/javascript"></script>
 14 </head>
 15 <body>
 16 <a name="top"></a>
 17 
 18 <!--done-->
 19 <div id="home">
 20 <div id="header">
 21     <div id="blogTitle">
 22     <a id="lnkBlogLogo" href="http://www.cnblogs.com/gode/"><img id="blogLogo" src="/Skins/custom/images/logo.gif" alt="杩斿洖涓婚〉" /></a>            
 23         
 24 <!--done-->
 25 <h1><a id="Header1_HeaderTitle" class="headermaintitle" href="http://www.cnblogs.com/gode/">Hello.World!</a></h1>
 26 <h2></h2>
 27 
 28 
 29 
 30         
 31     </div><!--end: blogTitle 鍗氬鐨勬爣棰樺拰鍓爣棰? -->
 32     <div id="navigator">
 33         
 34 <ul id="navList">
 35 <li><a id="MyLinks1_HomeLink" class="menu" href="http://www.cnblogs.com/">鍗氬鍥?</a></li>
 36 <li><a id="MyLinks1_MyHomeLink" class="menu" href="http://www.cnblogs.com/gode/">棣栭〉</a></li>
 37 <li><a id="MyLinks1_NewPostLink" class="menu" rel="nofollow" href="https://i.cnblogs.com/EditPosts.aspx?opt=1">鏂伴殢绗?</a></li>
 38 <li><a id="MyLinks1_ContactLink" class="menu" rel="nofollow" href="http://msg.cnblogs.com/send/Hello.World%21">鑱旂郴</a></li>
 39 <li><a id="MyLinks1_Syndication" class="menu" href="http://www.cnblogs.com/gode/rss">璁㈤槄</a>
 40 <!--<a id="MyLinks1_XMLLink" class="aHeaderXML" href="http://www.cnblogs.com/gode/rss"><img src="//www.cnblogs.com/images/xml.gif" alt="璁㈤槄" /></a>--></li>
 41 <li><a id="MyLinks1_Admin" class="menu" rel="nofollow" href="https://i.cnblogs.com/">绠$悊</a></li>
 42 </ul>
 43         <div class="blogStats">
 44             
 45             
 46 <span id="stats_post_count">闅忕瑪 - 2&nbsp; </span>
 47 <span id="stats_article_count">鏂囩珷 - 0&nbsp; </span>
 48 <span id="stats-comment_count">璇勮 - 0</span>
 49 
 50             
 51         </div><!--end: blogStats -->
 52     </div><!--end: navigator 鍗氬瀵艱埅鏍? -->
 53 </div><!--end: header 澶撮儴 -->
 54 
 55 <div id="main">
 56     <div id="mainContent">
 57     <div class="forFlow">
 58         
 59 <div id="post_detail">
 60 <!--done-->
 61 <div id="topics">
 62     <div class = "post">
 63         <h1 class = "postTitle">
 64             <a id="cb_post_title_url" class="postTitle2" href="http://www.cnblogs.com/gode/p/5812013.html">浣跨敤UDP杩涜鏁版嵁鍙戦?佺殑瀹炰緥涓?</a>
 65         </h1>
 66         <div class="clear"></div>
 67         <div class="postBody">
 68             <div id="cnblogs_post_body"><p>棣栧厛濡傛灉TCP瀛﹁繃浠ュ悗锛屽啀鐪婾DP杩涜鏁版嵁浼犺緭涔熸槸澶у悓灏忓紓鐨勶紝鍙槸鐢ㄥ埌鐨勭被涓嶅悓</p>
 69 <p>UDP杩涜浼犺緭闇?瑕丏ataSocket鍜孌atapacket绫伙紝Datapacket鍙暟鎹姤锛屾瘡涓?涓暟鎹姤涓嶈兘澶т簬64k锛岄兘璁板綍鐫?鏁版嵁淇℃伅锛屽彂閫佺鐨処P銆佺鍙e彿锛?</p>
 70 <p>浠ュ強瑕佸彂閫佸埌鐨勬帴鏀剁鐨処P銆佺鍙e彿銆?</p>
 71 <p>UDP杩涜浼犺緭鏄皢鏁版嵁鍏ㄩ儴鎵撳寘锛岀劧鍚庝竴璧峰彂杩囧幓锛屽鏄撻?犳垚鏁版嵁涓㈠け锛屼絾閫熷害杈冨揩锛屾瘮濡傝涓嬭澆涓?涓數褰憋紝缂哄け鍑犱睛骞舵病鏈変粈涔堝獎鍝嶏紝浣嗛渶瑕佸揩閫熶笅杞斤紝杩欎釜鏃跺?欏彲浠ラ?夋嫨UDP杩涜浼犺緭锛屾墍璋撳悇鏈夋墍闀匡紝鍏蜂綋閫夋嫨閭g鏂瑰紡杩樻槸瑕佺湅鍏蜂綋闇?瑕併??</p>
 72 <p>鎺ヤ笅鏉ラ檮鍔犱竴涓猆DP杩涜鏂囧瓧浼犺緭锛岀劧鍚庢帴鏀剁鎵撳嵃鍒版帶鍒跺彴涓?</p>
 73 <div class="cnblogs_code">
 74 <pre><span > 1</span> <span >package</span><span > com.UDP.java;
 75 </span><span > 2</span> 
 76 <span > 3</span> <span >import</span><span > java.io.IOException;
 77 </span><span > 4</span> <span >import</span><span > java.net.DatagramPacket;
 78 </span><span > 5</span> <span >import</span><span > java.net.DatagramSocket;
 79 </span><span > 6</span> <span >import</span><span > java.net.InetAddress;
 80 </span><span > 7</span> <span >import</span><span > org.junit.Test;
 81 </span><span > 8</span> 
 82 <span > 9</span> <span >public</span> <span >class</span><span > TestUDP {
 83 </span><span >10</span>     <span >//</span><span > 鍙戦?佺</span>
 84 <span >11</span> <span >    @Test
 85 </span><span >12</span>     <span >public</span> <span >void</span><span > send() {
 86 </span><span >13</span>         DatagramSocket ds = <span >null</span><span >;
 87 </span><span >14</span>         <span >try</span><span > {
 88 </span><span >15</span>             ds = <span >new</span><span > DatagramSocket();
 89 </span><span >16</span>             <span >//</span><span > 鍒涘緩涓?涓暟鎹姤锛屾瘡涓?涓暟鎹姤涓嶈兘澶т簬64k锛岄兘璁板綍鐫?鏁版嵁淇℃伅锛屽彂閫佺鐨処P銆佺鍙e彿锛屼互鍙婅鍙戦?佸埌
 90 </span><span >17</span>             <span >//</span><span > 鐨勬帴鏀剁鐨処P銆佺鍙e彿銆?</span>
 91 <span >18</span>             <span >byte</span>[] b = "鎴戞槸鍙戦?佺"<span >.getBytes();
 92 </span><span >19</span>             DatagramPacket pack = <span >new</span> DatagramPacket(b, 0<span >, b.length, 
 93 </span><span >20</span>                     InetAddress.getByName("192.168.1.101"), 9090<span >);
 94 </span><span >21</span> <span >            ds.send(pack);
 95 </span><span >22</span>         } <span >catch</span><span > (IOException e) {
 96 </span><span >23</span> <span >            e.printStackTrace();
 97 </span><span >24</span>         } <span >finally</span><span > {
 98 </span><span >25</span>             <span >if</span> (ds != <span >null</span><span >) {
 99 </span><span >26</span> <span >                ds.close();
100 </span><span >27</span> <span >            }
101 </span><span >28</span> <span >        }
102 </span><span >29</span> <span >    }
103 </span><span >30</span> 
104 <span >31</span>     <span >//</span><span > 鎺ユ敹绔?</span>
105 <span >32</span> <span >    @Test
106 </span><span >33</span>     <span >public</span> <span >void</span><span > receive() {
107 </span><span >34</span>         DatagramSocket ds = <span >null</span><span >;
108 </span><span >35</span>         <span >try</span><span > {
109 </span><span >36</span>             ds = <span >new</span> DatagramSocket(9090<span >);
110 </span><span >37</span>             <span >byte</span>[] b = <span >new</span> <span >byte</span>[1024<span >];
111 </span><span >38</span>             DatagramPacket pack = <span >new</span> DatagramPacket(b, 0<span >, b.length);
112 </span><span >39</span> <span >            ds.receive(pack);
113 </span><span >40</span>             String str = <span >new</span> String(pack.getData(), 0<span >, pack.getLength());
114 </span><span >41</span> <span >            System.out.println(str);
115 </span><span >42</span>         }<span >catch</span><span > (IOException e) {
116 </span><span >43</span> <span >            e.printStackTrace();
117 </span><span >44</span> <span >        }
118 </span><span >45</span>         <span >finally</span><span >{
119 </span><span >46</span>             <span >if</span>(ds != <span >null</span><span >){
120 </span><span >47</span> <span >                ds.close();
121 </span><span >48</span> <span >            }
122 </span><span >49</span> <span >        }
123 </span><span >50</span> <span >    }
124 </span><span >51</span> }</pre>
125 </div>
126 <p>&nbsp;</p></div><div id="MySignature"></div>
127 <div class="clear"></div>
128 <div id="blog_post_info_block">
129 <div id="BlogPostCategory"></div>
130 <div id="EntryTag"></div>
131 <div id="blog_post_info">
132 </div>
133 <div class="clear"></div>
134 <div id="post_next_prev"></div>
135 </div>
136 
137 
138         </div>
139         <div class = "postDesc">posted @ <span id="post-date">2016-08-26 23:29</span> <a href='http://www.cnblogs.com/gode/'>Hello.World!</a> 闃呰(<span id="post_view_count">...</span>) 璇勮(<span id="post_comment_count">...</span>)  <a href ="https://i.cnblogs.com/EditPosts.aspx?postid=5812013" rel="nofollow">缂栬緫</a> <a href="#" onclick="AddToWz(5812013);return false;">鏀惰棌</a></div>
140     </div>
141     <script type="text/javascript">var allowComments=true,cb_blogId=301422,cb_entryId=5812013,cb_blogApp=currentBlogApp,cb_blogUserGuid='a076c060-2898-e511-9fc1-ac853d9f53cc',cb_entryCreatedDate='2016/8/26 23:29:00';loadViewCount(cb_entryId);</script>
142     
143 </div><!--end: topics 鏂囩珷銆佽瘎璁哄鍣?-->
144 </div><a name="!comments"></a><div id="blog-comments-placeholder"></div><script type="text/javascript">var commentManager = new blogCommentManager();commentManager.renderComments(0);</script>
145 <div id='comment_form' class='commentform'>
146 <a name='commentform'></a>
147 <div id='divCommentShow'></div>
148 <div id='comment_nav'><span id='span_refresh_tips'></span><a href='javascript:void(0);' onclick='return RefreshCommentList();' id='lnk_RefreshComments' runat='server' clientidmode='Static'>鍒鋒柊璇勮</a><a href='#' onclick='return RefreshPage();'>鍒鋒柊椤甸潰</a><a href='#top'>杩斿洖椤墮儴</a></div>
149 <div id='comment_form_container'></div>
150 <div class='ad_text_commentbox' id='ad_text_under_commentbox'></div>
151 <div id='ad_t2'></div>
152 <div id='opt_under_post'></div>
153 <div id='ad_c1' class='c_ad_block'></div>
154 <div id='under_post_news'></div>
155 <div id='ad_c2' class='c_ad_block'></div>
156 <div id='under_post_kb'></div>
157 <div id='HistoryToday' class='c_ad_block'></div>
158 <script type='text/javascript'>
159 $(function () {
160     setTimeout(function () { incrementViewCount(cb_entryId); }, 50);
161     deliverAdT2();
162     deliverAdC1();
163     deliverAdC2();    
164     loadNewsAndKb();
165     loadBlogSignature();
166     LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid);
167     GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate);
168     loadOptUnderPost();
169     GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate);    
170 });
171 </script>
172 </div>
173 
174 
175     </div><!--end: forFlow -->
176     </div><!--end: mainContent 涓諱綋鍐呭瀹瑰櫒-->
177 
178     <div id="sideBar">
179         <div id="sideBarMain">
180             
181 <!--done-->
182 <div class="newsItem">
183 <h3 class="catListTitle">鍏憡</h3>
184     <div id="blog-news"></div><script type="text/javascript">loadBlogNews();</script>
185 </div>
186 
187             <div id="blog-calendar" ></div><script type="text/javascript">loadBlogDefaultCalendar();</script>
188             
189             <div id="leftcontentcontainer">
190                 <div id="blog-sidecolumn"></div><script type="text/javascript">loadBlogSideColumn();</script>
191             </div>
192             
193         </div><!--end: sideBarMain -->
194     </div><!--end: sideBar 渚ц竟鏍忓鍣? -->
195     <div class="clear"></div>
196     </div><!--end: main -->
197     <div class="clear"></div>
198     <div id="footer">
199         
200 <!--done-->
201 Copyright &copy;2016 Hello.World!
202     </div><!--end: footer -->
203 </div><!--end: home 鑷畾涔夌殑鏈?澶у鍣? -->
204 </body>
205 </html>


並不是想象中的會將我寫的博客打印出來,而是打印出了頁面的HTML布局代碼

而教程中,使用Tomcat服務器,URL地址指定的是一個txt文檔,啟動Tomcat,可以將該txt文檔中的內容打印出來

分析:這個URL所指的地址被封裝了,不能直接找到服務器的文檔(ps:如果能的話那豈不是亂套了,服務器裡存儲的東西想看就看)

如果此文件非文本文件呢?

我要將此文件寫入本地,使用url.openConnection()方法,返回一個URLConnection的對象

具體代碼如下

 1 //如果既有數據的讀入,又有數據的輸出,就要考慮使用URLConnection
 2         URLConnection urlConnection = url.openConnection();
 3         InputStream is1 = urlConnection.getInputStream();
 4         //之前打印已經發現是HTML類型的文件了,所以在這裡定義成一個.html類型的文件,看看效果如何
 5         FileOutputStream fos = new FileOutputStream(new File("aaa.html"));
 6         byte[] b1 = new byte[1024];
 7         int length1;
 8         while((length1 = is1.read(b1)) != -1){
 9             fos.write(b1, 0, length1);
10         }
11         fos.close();
12         is1.close();

激動人心的時刻到了,打印出來的HTML文件真的是HTML文件,具體內容如下(沒有亂碼了)

  1 <!DOCTYPE html>
  2 <html lang="zh-cn">
  3 <head>
  4 <meta charset="utf-8"/>
  5 <title>使用UDP進行數據發送的實例一 - Hello.World! - 博客園</title>
  6 <link type="text/css" rel="stylesheet" href="/bundles/blog-common.css?v=Ugwf7ssw_T-Y4bsdVDPHPhPR9NEESRNHOF-E8IRqEJk1"/>
  7 <link id="MainCss" type="text/css" rel="stylesheet" href="/skins/CodingLife/bundle-CodingLife.css?v=dE43LeVMdRWr6dflRs5MpsAmgg8oyLrU-UvBlmYDLvg1"/>
  8 <link title="RSS" type="application/rss+xml" rel="alternate" href="http://www.cnblogs.com/gode/rss"/>
  9 <link title="RSD" type="application/rsd+xml" rel="EditURI" href="http://www.cnblogs.com/gode/rsd.xml"/>
 10 <link type="application/wlwmanifest+xml" rel="wlwmanifest" href="http://www.cnblogs.com/gode/wlwmanifest.xml"/>
 11 <script src="//common.cnblogs.com/script/jquery.js" type="text/javascript"></script>  
 12 <script type="text/javascript">var currentBlogApp = 'gode', cb_enable_mathjax=false;var isLogined=false;</script>
 13 <script src="/bundles/blog-common.js?v=Q7JqGMCRFJwGRojUTJLkQ6nIu4kUBVwm5mErn4um_MM1" type="text/javascript"></script>
 14 </head>
 15 <body>
 16 <a name="top"></a>
 17 
 18 <!--done-->
 19 <div id="home">
 20 <div id="header">
 21     <div id="blogTitle">
 22     <a id="lnkBlogLogo" href="http://www.cnblogs.com/gode/"><img id="blogLogo" src="/Skins/custom/images/logo.gif" alt="返回主頁" /></a>            
 23         
 24 <!--done-->
 25 <h1><a id="Header1_HeaderTitle" class="headermaintitle" href="http://www.cnblogs.com/gode/">Hello.World!</a></h1>
 26 <h2></h2>
 27 
 28 
 29 
 30         
 31     </div><!--end: blogTitle 博客的標題和副標題 -->
 32     <div id="navigator">
 33         
 34 <ul id="navList">
 35 <li><a id="MyLinks1_HomeLink" class="menu" href="http://www.cnblogs.com/">博客園</a></li>
 36 <li><a id="MyLinks1_MyHomeLink" class="menu" href="http://www.cnblogs.com/gode/">首頁</a></li>
 37 <li><a id="MyLinks1_NewPostLink" class="menu" rel="nofollow" href="https://i.cnblogs.com/EditPosts.aspx?opt=1">新隨筆</a></li>
 38 <li><a id="MyLinks1_ContactLink" class="menu" rel="nofollow" href="http://msg.cnblogs.com/send/Hello.World%21">聯系</a></li>
 39 <li><a id="MyLinks1_Syndication" class="menu" href="http://www.cnblogs.com/gode/rss">訂閱</a>
 40 <!--<a id="MyLinks1_XMLLink" class="aHeaderXML" href="http://www.cnblogs.com/gode/rss"><img src="//www.cnblogs.com/images/xml.gif" alt="訂閱" /></a>--></li>
 41 <li><a id="MyLinks1_Admin" class="menu" rel="nofollow" href="https://i.cnblogs.com/">管理</a></li>
 42 </ul>
 43         <div class="blogStats">
 44             
 45             
 46 <span id="stats_post_count">隨筆 - 2&nbsp; </span>
 47 <span id="stats_article_count">文章 - 0&nbsp; </span>
 48 <span id="stats-comment_count">評論 - 0</span>
 49 
 50             
 51         </div><!--end: blogStats -->
 52     </div><!--end: navigator 博客導航欄 -->
 53 </div><!--end: header 頭部 -->
 54 
 55 <div id="main">
 56     <div id="mainContent">
 57     <div class="forFlow">
 58         
 59 <div id="post_detail">
 60 <!--done-->
 61 <div id="topics">
 62     <div class = "post">
 63         <h1 class = "postTitle">
 64             <a id="cb_post_title_url" class="postTitle2" href="http://www.cnblogs.com/gode/p/5812013.html">使用UDP進行數據發送的實例一</a>
 65         </h1>
 66         <div class="clear"></div>
 67         <div class="postBody">
 68             <div id="cnblogs_post_body"><p>首先如果TCP學過以後,再看UDP進行數據傳輸也是大同小異的,只是用到的類不同</p>
 69 <p>UDP進行傳輸需要DataSocket和Datapacket類,Datapacket叫數據報,每一個數據報不能大於64k,都記錄著數據信息,發送端的IP、端口號,</p>
 70 <p>以及要發送到的接收端的IP、端口號。</p>
 71 <p>UDP進行傳輸是將數據全部打包,然後一起發過去,容易造成數據丟失,但速度較快,比如要下載一個電影,缺失幾偵並沒有什麼影響,但需要快速下載,這個時候可以選擇UDP進行傳輸,所謂各有所長,具體選擇那種方式還是要看具體需要。</p>
 72 <p>接下來附加一個UDP進行文字傳輸,然後接收端打印到控制台上</p>
 73 <div class="cnblogs_code">
 74 <pre><span > 1</span> <span >package</span><span > com.UDP.java;
 75 </span><span > 2</span> 
 76 <span > 3</span> <span >import</span><span > java.io.IOException;
 77 </span><span > 4</span> <span >import</span><span > java.net.DatagramPacket;
 78 </span><span > 5</span> <span >import</span><span > java.net.DatagramSocket;
 79 </span><span > 6</span> <span >import</span><span > java.net.InetAddress;
 80 </span><span > 7</span> <span >import</span><span > org.junit.Test;
 81 </span><span > 8</span> 
 82 <span > 9</span> <span >public</span> <span >class</span><span > TestUDP {
 83 </span><span >10</span>     <span >//</span><span > 發送端</span>
 84 <span >11</span> <span >    @Test
 85 </span><span >12</span>     <span >public</span> <span >void</span><span > send() {
 86 </span><span >13</span>         DatagramSocket ds = <span >null</span><span >;
 87 </span><span >14</span>         <span >try</span><span > {
 88 </span><span >15</span>             ds = <span >new</span><span > DatagramSocket();
 89 </span><span >16</span>             <span >//</span><span > 創建一個數據報,每一個數據報不能大於64k,都記錄著數據信息,發送端的IP、端口號,以及要發送到
 90 </span><span >17</span>             <span >//</span><span > 的接收端的IP、端口號。</span>
 91 <span >18</span>             <span >byte</span>[] b = "我是發送端"<span >.getBytes();
 92 </span><span >19</span>             DatagramPacket pack = <span >new</span> DatagramPacket(b, 0<span >, b.length, 
 93 </span><span >20</span>                     InetAddress.getByName("192.168.1.101"), 9090<span >);
 94 </span><span >21</span> <span >            ds.send(pack);
 95 </span><span >22</span>         } <span >catch</span><span > (IOException e) {
 96 </span><span >23</span> <span >            e.printStackTrace();
 97 </span><span >24</span>         } <span >finally</span><span > {
 98 </span><span >25</span>             <span >if</span> (ds != <span >null</span><span >) {
 99 </span><span >26</span> <span >                ds.close();
100 </span><span >27</span> <span >            }
101 </span><span >28</span> <span >        }
102 </span><span >29</span> <span >    }
103 </span><span >30</span> 
104 <span >31</span>     <span >//</span><span > 接收端</span>
105 <span >32</span> <span >    @Test
106 </span><span >33</span>     <span >public</span> <span >void</span><span > receive() {
107 </span><span >34</span>         DatagramSocket ds = <span >null</span><span >;
108 </span><span >35</span>         <span >try</span><span > {
109 </span><span >36</span>             ds = <span >new</span> DatagramSocket(9090<span >);
110 </span><span >37</span>             <span >byte</span>[] b = <span >new</span> <span >byte</span>[1024<span >];
111 </span><span >38</span>             DatagramPacket pack = <span >new</span> DatagramPacket(b, 0<span >, b.length);
112 </span><span >39</span> <span >            ds.receive(pack);
113 </span><span >40</span>             String str = <span >new</span> String(pack.getData(), 0<span >, pack.getLength());
114 </span><span >41</span> <span >            System.out.println(str);
115 </span><span >42</span>         }<span >catch</span><span > (IOException e) {
116 </span><span >43</span> <span >            e.printStackTrace();
117 </span><span >44</span> <span >        }
118 </span><span >45</span>         <span >finally</span><span >{
119 </span><span >46</span>             <span >if</span>(ds != <span >null</span><span >){
120 </span><span >47</span> <span >                ds.close();
121 </span><span >48</span> <span >            }
122 </span><span >49</span> <span >        }
123 </span><span >50</span> <span >    }
124 </span><span >51</span> }</pre>
125 </div>
126 <p>&nbsp;</p></div><div id="MySignature"></div>
127 <div class="clear"></div>
128 <div id="blog_post_info_block">
129 <div id="BlogPostCategory"></div>
130 <div id="EntryTag"></div>
131 <div id="blog_post_info">
132 </div>
133 <div class="clear"></div>
134 <div id="post_next_prev"></div>
135 </div>
136 
137 
138         </div>
139         <div class = "postDesc">posted @ <span id="post-date">2016-08-26 23:29</span> <a href='http://www.cnblogs.com/gode/'>Hello.World!</a> 閱讀(<span id="post_view_count">...</span>) 評論(<span id="post_comment_count">...</span>)  <a href ="https://i.cnblogs.com/EditPosts.aspx?postid=5812013" rel="nofollow">編輯</a> <a href="#" onclick="AddToWz(5812013);return false;">收藏</a></div>
140     </div>
141     <script type="text/javascript">var allowComments=true,cb_blogId=301422,cb_entryId=5812013,cb_blogApp=currentBlogApp,cb_blogUserGuid='a076c060-2898-e511-9fc1-ac853d9f53cc',cb_entryCreatedDate='2016/8/26 23:29:00';loadViewCount(cb_entryId);</script>
142     
143 </div><!--end: topics 文章、評論容器-->
144 </div><a name="!comments"></a><div id="blog-comments-placeholder"></div><script type="text/javascript">var commentManager = new blogCommentManager();commentManager.renderComments(0);</script>
145 <div id='comment_form' class='commentform'>
146 <a name='commentform'></a>
147 <div id='divCommentShow'></div>
148 <div id='comment_nav'><span id='span_refresh_tips'></span><a href='javascript:void(0);' onclick='return RefreshCommentList();' id='lnk_RefreshComments' runat='server' clientidmode='Static'>刷新評論</a><a href='#' onclick='return RefreshPage();'>刷新頁面</a><a href='#top'>返回頂部</a></div>
149 <div id='comment_form_container'></div>
150 <div class='ad_text_commentbox' id='ad_text_under_commentbox'></div>
151 <div id='ad_t2'></div>
152 <div id='opt_under_post'></div>
153 <div id='ad_c1' class='c_ad_block'></div>
154 <div id='under_post_news'></div>
155 <div id='ad_c2' class='c_ad_block'></div>
156 <div id='under_post_kb'></div>
157 <div id='HistoryToday' class='c_ad_block'></div>
158 <script type='text/javascript'>
159 $(function () {
160     setTimeout(function () { incrementViewCount(cb_entryId); }, 50);
161     deliverAdT2();
162     deliverAdC1();
163     deliverAdC2();    
164     loadNewsAndKb();
165     loadBlogSignature();
166     LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid);
167     GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate);
168     loadOptUnderPost();
169     GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate);    
170 });
171 </script>
172 </div>
173 
174 
175     </div><!--end: forFlow -->
176     </div><!--end: mainContent 主體內容容器-->
177 
178     <div id="sideBar">
179         <div id="sideBarMain">
180             
181 <!--done-->
182 <div class="newsItem">
183 <h3 class="catListTitle">公告</h3>
184     <div id="blog-news"></div><script type="text/javascript">loadBlogNews();</script>
185 </div>
186 
187             <div id="blog-calendar" ></div><script type="text/javascript">loadBlogDefaultCalendar();</script>
188             
189             <div id="leftcontentcontainer">
190                 <div id="blog-sidecolumn"></div><script type="text/javascript">loadBlogSideColumn();</script>
191             </div>
192             
193         </div><!--end: sideBarMain -->
194     </div><!--end: sideBar 側邊欄容器 -->
195     <div class="clear"></div>
196     </div><!--end: main -->
197     <div class="clear"></div>
198     <div id="footer">
199         
200 <!--done-->
201 Copyright &copy;2016 Hello.World!
202     </div><!--end: footer -->
203 </div><!--end: home 自定義的最大容器 -->
204 </body>
205 </html>


這裡處理異常的方式是直接throws出去了,不符合規范,正常應該全都try-catch-finally,原諒我懶了~~~

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved