我有一个猜谜游戏。它分为两个部分。服务器和客户端。这两个类都包含在这篇文章中。逻辑检查用户输入是否在一定范围内。如果检查成功,则将用户输入与逻辑猜测进行比较。逻辑必须自己循环,让用户尝试更多的“回合”。
我唯一的问题是该代码退出逻辑循环,并且没有第二次进行迭代,依此类推。
这是我的服务器代码:
public class ServerNum {
public static void main(String[] args) throws IOException {
adivinarNum juego = new adivinarNum();
ServerSocket socket = null;
Socket client = null;
String resultado;
boolean correcto = false;
int intentos;
try {
socket = new ServerSocket(1234);
} catch(IOException ioe) {
System.err.println(ioe);
return; }
System.out.println("El servidor sigue funcionando...");
client = socket.accept();
System.out.println("El cliente se ha conectado");
DataInputStream in = new DataInputStream(new BufferedInputStream(client.getInputStream()));
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
while(!correcto) {
intentos = in.readInt();
resultado = juego.adivinar(intentos);
correcto = juego.getCorrecto();
out.writeUTF(resultado);
out.writeBoolean(correcto);
out.flush();
if(correcto == false){
client = socket.accept();
intentos = in.readInt();
resultado = juego.adivinar(intentos);
correcto = juego.getCorrecto();
out.writeUTF(resultado);
out.writeBoolean(correcto);
out.flush();
} else {
client.close();
socket.close(); } } } }
和客户代码:
public class ClientNum {
public static void main(String[] args) throws IOException {
System.out.println("This is Number Guessing Game. \nChoose any number between 1 to 1000 : ");
Scanner keyboard = new Scanner(System.in);
int attempt = 0;
try {
attempt = keyboard.nextInt();
if(attempt < 1 || attempt > 999) {
System.out.println("Your number is too large/small, please make a guess between 1 to 1000");
attempt = keyboard.nextInt(); } }
catch(NumberFormatException nfe) {
System.out.println("Just choose numbers! Try again");
attempt = keyboard.nextInt(); }
try {
Socket server = new Socket("localhost", 1234);
System.out.println("Connecting...");
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(server.getOutputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(server.getInputStream()));
out.writeInt(attempt);
out.flush();
System.out.println("Our server is still running...");
String result = in.readUTF();
boolean correct = in.readBoolean();
System.out.println(result);
while (!correct) {
attempt = keyboard.nextInt();
out.writeInt(attempt);
out.flush();
System.out.println("Our server is still running...");
result = in.readUTF();
System.out.println(result);
correct = in.readBoolean(); }
server.close();
System.out.println("Finish. Thank you");
System.exit(0);
} catch(IOException ioe) {
System.err.println(ioe); } } }
我的错误在哪里?
socket.accept
用于接受与客户端的连接。这意味着它用于开始与客户端进行通信,因此,每个连接仅需要调用一次。同样,您的客户端在得到正确答案后立即断开连接,然后到达其main()
方法的结尾,这意味着程序在此处结束。
您应该设计程序以建立连接,然后在一个while
循环(通常称为“游戏循环” )中玩游戏代码,直到用户不再希望玩游戏为止。当用户不再希望玩游戏时,请结束循环,然后让其关闭与服务器的连接,以使应用程序可以正常关闭。
应当注意,该accept
方法具有与之相关的效率开销,因此,如果您不必经常调用该方法,则该程序将更高效地运行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句