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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值