1. 程式人生 > >java高階特性與實戰專案 ——第五章: 網路程式設計

java高階特性與實戰專案 ——第五章: 網路程式設計

1.編寫一個程式,查詢指定域名為www.taobao.com的所以可能的ip地址。
public class Tb {

	public static void main(String[] args) {
	
		        try {  
		            InetAddress add=InetAddress.getByName("www.taobao.com");  //查詢指定ip名
		            System.out.println("---------------淘寶的主伺服器地址------------------");  
		            System.out.println(add);  
		            System.out.println("---------------淘寶的所有伺服器地址-----------------");  
		            InetAddress []  add1=InetAddress.getAllByName("taobao.com");  
		            System.out.println(add);
		            for (int i = 0; i < add1.length; i++) {    //利用迴圈列印
		                System.out.println("www."+add1[i]);  
		            } 
		        } catch (UnknownHostException e) {  
		            e.printStackTrace();  
		        }  
	}

}
2.模擬使用者登入,預設使用者資料,提示登入成功或不成功的原因。
/*
 * 服務端
 */
public class Server {

	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(8800);
			Socket socket = serverSocket.accept();
			InputStream is = socket.getInputStream(); // 讀取流
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String info = "";
			StringBuffer sb = new StringBuffer();
			while ((info = br.readLine()) != null) {
				System.out.println("我是伺服器,客戶端登入資訊為:" + info);
				sb.append(info);
			}
			socket.shutdownInput(); // 先關閉輸入流
			OutputStream os = null;
			String sum = sb.toString();
			if (sum.equals("使用者1") || sum.equals("使用者2") || sum.equals("使用者3")) { // 判斷使用者名稱
				info = "歡迎你,登入成功!";
				os = socket.getOutputStream();
				os.write(info.getBytes());
				System.out.println("存在該使用者,使用者登入成功");
			} else {
				info = "對不起,沒有該使用者,登入失敗";
				os = socket.getOutputStream();
				os.write(info.getBytes());
				System.out.println("對不起,沒有該使用者,已通知客戶端登入失敗");
			}
			os.close(); // 關流
			br.close();
			is.close();
			socket.close();
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

/*
 * 客戶端
 */
public class Analog {

	public static void main(String[] args) {
		 try {  
	            Socket socket=new Socket("localhost",8800);  
	            Scanner input=new Scanner(System.in);  
	            System.out.print("請輸入使用者名稱:");  
	            String info=input.next();  
	            OutputStream os=socket.getOutputStream();  
	            byte [] infos=info.getBytes();  
	            os.write(infos);  
	            //接收  
	            socket.shutdownOutput();//先關閉輸出流  
	  
	            InputStream is=socket.getInputStream();  
	            BufferedReader br=new BufferedReader(new InputStreamReader(is));  
	            String reply;  
	            while ((reply=br.readLine())!=null){  
	                System.out.println("我是客戶端,伺服器的響應為:"+reply);  
	            }  
	            br.close();  
	            is.close();  
	            os.close();  
	            socket.close();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	}
}