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();
			}
			
		}

	}

}

猜你喜欢

转载自blog.csdn.net/duanhaifeng55/article/details/80469905