第5章 课后作业

第2题,查找指定域名为www.taobao.com的所有可能的IP地址

import java.net.InetAddress;

public class ObtainIp {
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[] add = InetAddress.getAllByName("www.taobao.com");
for (int i = 0; i < add.length; i++) {
System.out.println(add[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}

}

第3题  模拟用户登录

import java.net.ServerSocket;
import java.net.Socket;


public class LoginServer {
public static void main(String[] args) {
ServerSocket ss = null;
Socket socket = null;
try {
ss = new ServerSocket(8877);
while (true) {
socket = ss.accept();
LoginThread lt = new LoginThread(socket);
lt.start();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

}

import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.io.OutputStream;


public class LoginThread extends Thread {
Socket socket = null;


public LoginThread(Socket socket) {
super();
this.socket = socket;
}


public void run() {
ArrayList<String> loginName = new ArrayList<String>();
loginName.add("张三");
loginName.add("李四");
loginName.add("王五");
InputStream is = null;
OutputStream os = null;
try {
is = socket.getInputStream();
byte[] buf = new byte[1024];
int len = -1;
String str = null;
if ((len = is.read(buf)) != -1) {
str = new String(buf, 0, len);
System.out.println("我是服务器,客户的登录信息为:" + str);


os = socket.getOutputStream();
if (loginName.contains(str)) {
System.out.println("存在该用户,登录成功!");
os.write("存在该用户,登录成功!".getBytes());
} else {
System.out.println("对不起,没有该用户,已通知客户端登录失败!");
os.write("对不起,没有该用户".getBytes());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

}

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;


public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("输入用户名:");
String name = input.next();
try {
Socket socket = new Socket("localhost", 8877);
OutputStream out = socket.getOutputStream();
out.write(name.getBytes());
socket.shutdownOutput();
InputStream is = socket.getInputStream();
byte[] buf = new byte[1024];
int len = -1;
String str = null;
if ((len = is.read(buf)) != -1) {
str = new String(buf, 0, len);
System.out.println("服务器返回的内容是:"+str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

猜你喜欢

转载自blog.csdn.net/weixin_41880408/article/details/80446417