课后练习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();
}
}
}
高级特性 第5章
最新推荐文章于 2022-09-19 09:07:27 发布