標籤:綁定 cal 資料 dem 組成 print 資源 source sde
Java網路通訊非常簡單,伺服器端通過ServerSocket建立監聽,用戶端通過Socket串連到指定伺服器後,通訊雙方就可以通過IO流進行通訊。
IP地址用於唯一地標識網路中的一個通訊實體。連接埠用於表示資料交給哪個通訊程式處理。
公認連接埠從0到1023,緊密綁定一些特定的服務。註冊連接埠從1024到49151,應用程式通常應該使用這個範圍的連接埠。動態連接埠從49152到65535,是應用程式使用的動態連接埠,應用程式一般不會主動使用這些連接埠。
package com.ivy.net;import java.net.InetAddress;public class InetAddressDemo { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub InetAddress ip = InetAddress.getByName("www.google.com"); System.out.println("crazyit isReachable : " + ip.isReachable(2000)); System.out.println(ip.getHostAddress()); InetAddress local = InetAddress.getByAddress(new byte[]{127,0,0,1}); System.out.println("local isReachable : " + local.isReachable(2000)); System.out.println(local.getHostAddress()); }}
當URL地址裡包含非西歐字元的字串時,系統會將這些非西歐字串轉換成application/x-www-form-urlencoded MIME字串。這就需要URLDecoder和URLEncoder類。只包含西歐字元的一般字元串無須轉換。
package com.ivy.net;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.net.URLEncoder;public class URLDecoderDemo { public static void main(String[] args) throws UnsupportedEncodingException { // TODO Auto-generated method stub String keyWord = URLDecoder.decode("%B7%E8%BF%F1Java", "GBK"); System.out.println(keyWord); String urlString = URLEncoder.encode("瘋狂Java講義", "GBK"); System.out.println(urlString); }}
通常情況下,URL可以由協議名/主機/連接埠和資源群組成,即如下格式
protocol://host:port/resourceName
eg. http://www.crazyit.org/index.php
使用Socket通訊
package com.ivy.net;import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;public class Server { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub ServerSocket ss = new ServerSocket(30000); while(true) { Socket s = ss.accept(); PrintStream ps = new PrintStream(s.getOutputStream()); ps.println("Hello"); ps.close(); s.close(); } }}
package com.ivy.net;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.Socket;public class Client { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub Socket socket = new Socket("127.0.0.1", 30000); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line = br.readLine(); System.out.println("data from server : " + line); br.close(); socket.close(); }}
《瘋狂Java講義》(三十五)---- 網路編程