高级特性 第5章

课后练习2:
package c2;

import java.net.InetAddress;

public class C2 {
	public static void main(String[] args) {
		try {
			System.out.println("-----淘宝的主服务器地址-----");
			InetAddress add = InetAddress.getByName("www.taobao.com");
			System.out.println(add);
			System.out.println("-----淘宝的所有服务器地址-----");
			InetAddress[] add2 = InetAddress.getAllByName("www.taobao.com");
			for (int i = 0; i < add2.length; i++) {
				System.out.println(add2[i]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

课后练习3:
package c3;

import java.io.Serializable;

public class User implements Serializable{
	private String name;
	public User(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
}

package c3;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	public static void main(String[] args) {
		try {
			ServerSocket serversocket = new ServerSocket(9999);
			Socket socket = serversocket.accept();
			InputStream is = socket.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			User user = (User)ois.readObject();
			if((user)!=null) {
				System.out.println("我是服务器,客户登录信息为:"+user.getName());
				if(user.getName().equals("用户1")) {
					System.out.println("存在该用户,登录成功!");
				}else {
					System.out.println("对不起,没有该用户,已通知客户端登录失败");
				}
			}
			OutputStream os = socket.getOutputStream();
			String respond = null;
			if(user.getName().equals("用户1")) {
				respond = "欢迎你,登录成功!";
			}else {
				respond = "对不起,没有该用户,登录失败!";
			}
			os.write(respond.getBytes());
			os.close();
			ois.close();
			is.close();
			socket.close();
			serversocket.close();
		} catch (Exception e) {
			
		}
	}
}

package c3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Login {
	public static void main(String[] args) {
		try {
			Socket socket = new Socket("localhost",9999);
			OutputStream os = socket.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			Scanner input = new Scanner(System.in);
			System.out.print("请输入用户名:");
			String name = input.next();
			User user = new User(name);
			oos.writeObject(user);
			socket.shutdownOutput();
			InputStream is = socket.getInputStream();
			byte[] b = new byte[1024];
			int len = is.read(b);
			System.out.println(new String(b,0,len));
			is.close();
			oos.close();
			os.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值