我正在制作猜谜游戏。一切正常,但我有一个问题。我第一次要求一个号码它正确地说我是高还是低,但第二次没有说什么..
这是我的服务器和客户端代码:
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);
}
}
}
我将不胜感激任何帮助!谢谢你!
答案 0 :(得分:1)
socket.accept
用于接受与客户端的连接。这意味着它用于开始与客户端通信,因此,每个连接只需要调用一次。此外,您的客户端一旦得到正确的答案就会断开连接,然后到达其main()
方法的末尾,这意味着程序在那里结束。
您应该设计程序,以便建立连接,然后在while
循环内播放游戏代码,通常称为“游戏循环”,直到用户不再希望播放。当用户不再希望播放时,允许循环结束,然后让它关闭与服务器的连接,以便应用程序可以正常关闭。
应该注意的是accept
方法具有与之相关的效率开销,因此如果您不必经常调用它,程序将更有效地运行。