我正在做猜謎遊戲。所有工作正常,但我有一個問題。第一次,我要求一個數字它正確地說我是否更高或更低,但第二沒有說什麼都沒有..Java猜測遊戲服務器 - 客戶端
這是我的服務器和客戶端代碼:
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()',我不認爲這是正確的。 –