1. 程式人生 > >JAVA高階特性第五章課後習題

JAVA高階特性第五章課後習題

1.編寫一個程式,查詢指定域名www.taobao.com的所有可能的IP地址。

package kehouzuoye;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class AddressTest {

	public static void main(String[] args) {
		try {
			System.out.println("-----淘寶的主伺服器地址------");
			InetAddress ia = InetAddress.getByName("www.taobao.com");
			System.out.println(ia);
			System.out.println("-----淘寶的所有伺服器地址------");
			InetAddress [] ia1 = InetAddress.getAllByName("www.taobao.com");
			for (int i = 0; i < ia1.length; i++) {
				System.out.println(ia1[i]);
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

2.模擬使用者登陸,預設使用者資料,提示登陸成功或不成功的原因。

package kehouzuoye2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 伺服器類
 * @author 段海鋒
 *
 */
public class ServerTest {

	public static void main(String[] args) {
		ServerSocket ss=null;
		Socket sk=null;
		InputStream is=null;
		OutputStream os=null;
		try {
			 ss = new ServerSocket(9000);
			 sk=ss.accept();
			 is=sk.getInputStream();
			 byte b []= new byte[1024];
			 int len=is.read(b);
			 if(new String(b,0,len).equals("使用者1")) {
				 System.out.println("我是伺服器,客戶登陸的資訊為:"+new String(b,0,len));
			 }else {
				 System.out.println("我是伺服器,客戶登陸的資訊為:"+new String(b,0,len));
				 System.out.println("對不起,沒有該使用者,已通知客戶端登陸失敗!");
			 }
			 os=sk.getOutputStream();
			 String noni="登陸成功!";
				os.write(noni.getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				os.close();
				is.close();
				ss.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}

}
package kehouzuoye2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 客戶端類
 * @author 段海鋒
 *
 */
public class OutlookTest {

	public static void main(String[] args) {
		OutputStream os=null;
		Socket sk=null;
		InputStream is=null;
		try {
			 sk =new Socket("localhost", 9000);
			 os=sk.getOutputStream();
			String use="使用者1";
			os.write(use.getBytes());
		    is=sk.getInputStream();
			byte b [] = new byte[1024];
			int len=is.read(b);
			System.out.println("我是客戶端,伺服器的迴應是:"+new String(b,0,len));
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				is.close();
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}

	}

}