记一次作业
运行截图
Server
Client
完整代码
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
import java.util.Scanner;
public class ServerDemo {
private int flag;
public void server() throws IOException {
System.out.println("服务端启动,等待客户端连接。。。");
PrintWriter out = null;
Scanner getClient = null;
ServerSocket server = null;
Socket client = null;
this.setFlag();
try {
server = new ServerSocket(6666);
client = server.accept();
System.out.println(client.getInetAddress() + " 已成功连接到此台服务器上。");
out = new PrintWriter(client.getOutputStream());
out.println("欢迎来到猜数字小游戏(1-100)!!!");
out.flush();
getClient = new Scanner(client.getInputStream());
while (getClient.hasNextLine()) {
String returnMsg = null;
String tmp = getClient.nextLine();
if ("e".equals(tmp)) {
break;
} else if ("c".equals(tmp)) {
returnMsg = "欢迎来到新一轮的猜数字小游戏(1-100)!!!";
this.setFlag();
} else {
int clientInput = Integer.parseInt(tmp);
if (clientInput > flag) {
returnMsg = "你输入的数字大了!!!";
} else if (clientInput < flag) {
returnMsg = "你输入的数字小了!!!";
} else {
returnMsg = "恭喜你,猜中了!!!继续(输入c),退出(输入e)";
}
}
out.println(returnMsg);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
out.close();
getClient.close();
server.close();
}
}
public void setFlag() {
Random r = new Random();
flag = r.nextInt(100);
System.out.println("猜数字小游戏答案:flag = " + flag);
}
public static void main(String[] args) throws IOException {
new ServerDemo().server();
}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class ClientDemo {
public void client() throws IOException {
System.out.println("正在向服务器请求连接。。。");
Socket client = null;
Scanner getKey = null;
Scanner getServer = null;
PrintWriter out = null;
try {
client = new Socket("127.0.0.1", 6666);
getServer = new Scanner(client.getInputStream());
System.out.println(getServer.nextLine());
out = new PrintWriter(client.getOutputStream());
System.out.print("请输入数字:");
getKey = new Scanner(System.in);
while (getKey.hasNextLine()) {
out.println(getKey.nextLine());
out.flush();
try {
System.out.println("提示消息:" + getServer.nextLine());
System.out.print("请输入数字:");
} catch (Exception e) {
System.out.print("游戏结束!!!");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
getKey.close();
getServer.close();
out.close();
client.close();
}
}
public static void main(String[] args) throws IOException {
new ClientDemo().client();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)