Le serveur Java n’accepterait qu’une entrée de mon client

J’ai créé un serveur multithread qui se connecte à une firebase database MySQL et accepte les demandes d’un client. Le serveur doit toujours écouter les commandes du client, mais cela ne se produit pas. Il accepte simplement une commande qui l’envoie à la firebase database et obtient tout ce dont j’ai besoin, puis c’est fait. Il n’accepte plus de commandes. Je vous fournis le client et le serveur.

import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.rmi.ConnectException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; public class Airlines { public static void main(Ssortingng[] args) { ServerSocket serverSocket = null; Socket connection = null; int port = 1234; try{ serverSocket = new ServerSocket(port); while ((connection = serverSocket.accept())!=null){ System.out.println("Client connected!"); Thread client = new Thread (new AirlinesThread(connection)); client.start(); } }catch (IOException e){ System.out.println("Binding unsuccesful..."); } } } class AirlinesThread implements Runnable{ Socket connection = null; public AirlinesThread (Socket connection){ this.connection = connection; } private static Connection connect(Ssortingng url, Ssortingng user, Ssortingng password){ Connection result = null; try{ result = DriverManager.getConnection(url, user, password); System.out.println("Database connection successful!"); } catch(SQLException e){ System.out.println("Could not connect to the database!"); } return result; } Ssortingng url = "jdbc:mysql://localhost:3306/Airlines"; Ssortingng user = "root"; Ssortingng pass = "123456"; Connection link = AirlinesThread.connect(url, user, pass); Statement stmt = null; ResultSet resultSet = null; public void run() { PrintWriter socketOut = null; DataInputStream socketIn = null; try{ socketOut = new PrintWriter(this.connection.getOutputStream(),true); socketIn = new DataInputStream(this.connection.getInputStream()); int command; boolean exists = false; socketOut.flush(); loop:do{ socketOut.flush(); command = socketIn.readInt(); switch (command){ case 1: try{ stmt = link.createStatement(); resultSet = stmt.executeQuery("select Flight.id, Flight.Date, Flight.Time, Flight.Total_Flight_Time, Airports.Departure, Airports.Arrivals FROM Flight, Airports WHERE Flight.id = Airports.Flight"); socketOut.flush(); socketOut.println("FlightID\tDate\t\tTime\t\tTotal Time\tDeparture\tArrivals"); while (resultSet.next()) { socketOut.println(resultSet.getSsortingng("Flight.id")+"\t\t"+resultSet.getDate("Flight.Date")+"\t"+resultSet.getSsortingng("Flight.Time")+"\t"+resultSet.getSsortingng("Flight.Total_Flight_Time")+"\t\t"+resultSet.getSsortingng("Airports.Departure")+"\t"+resultSet.getSsortingng("Airports.Arrivals")); } } catch(SQLException e){ System.out.println("Something went wrong at 1"); } break; case 2: try{ stmt = link.createStatement(); resultSet = stmt.executeQuery("select Flight.id, Flight.Date, Flight.Time, Pilots.First_Name, Pilots.Last_Name from Flight RIGHT JOIN Pilots ON Flight.id = Pilots.FlightID;"); socketOut.flush(); socketOut.println("FlightID\tDate\t\tTime\t\tFirst Name\tLast Name"); exists = resultSet.next(); if(exists == false){ socketOut.flush(); socketOut.println("Wrong request!"); System.out.println("Wrong query at 2"); } while (resultSet.next()) { socketOut.flush(); socketOut.println(resultSet.getSsortingng("Flight.id")+"\t\t"+resultSet.getDate("Flight.Date")+"\t"+resultSet.getSsortingng("Flight.Time")+"\t"+resultSet.getSsortingng("Pilots.First_Name")+"\t\t"+resultSet.getSsortingng("Pilots.Last_Name")); } } catch(SQLException e){ System.out.println("Something went wrong at 2"); } break; case 3: try{ stmt = link.createStatement(); resultSet = stmt.executeQuery("select Food.Breakfast, Airplanes.Plane_Model FROM Food, Airplanes Where Food.FlightID=Airplanes.Plane_Model;"); exists = resultSet.next(); if(exists == false){ socketOut.flush(); socketOut.println("Wrong request!"); System.out.println("Wrong query at 3"); } while (resultSet.next()) { socketOut.flush(); socketOut.println(resultSet.getSsortingng("Food.Breakfast")+"\t\t"+resultSet.getSsortingng("Airplanes.Plane_Model")); } } catch(SQLException e){ System.out.println("Something went wrong at 3"); } break; case 0 : socketOut.flush(); socketOut.println("Exitting..."); break loop; default: System.out.println("Unknown command!"); socketOut.println("Unknown command!"); break; } }while(command!=0); System.out.println("Closing connection to the client!"); }catch (IOException e){ e.printStackTrace(); }finally{ try{ if (socketIn!=null) socketIn.close(); if (socketOut!=null) socketOut.close(); if (connection!=null) connection.close(); System.out.println("Connection to server closed!"); } catch(IOException e){ System.err.println("Could not close connection!"); } } try{ if(stmt != null) stmt.close(); if(resultSet != null) resultSet.close(); if(link != null) link.close(); System.out.println("Database connection closed successfully!"); }catch(SQLException ex){ System.out.println("Could not close connection to the database!"); } } } 

Le client:

 import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ConnectException; import java.net.Socket; import java.util.Scanner; public class AirlinesClient { public static void main(Ssortingng[] args) { Socket connection = null; Scanner socketIn = null; DataOutputStream socketOut = null; int port = 1234; Ssortingng host = "localhost"; Scanner keyIn = new Scanner(System.in); try{ try{ connection = new Socket(host,port); socketIn = new Scanner(new BufferedReader(new InputStreamReader(connection.getInputStream()))); socketOut = new DataOutputStream(connection.getOutputStream()); }catch(ConnectException e){ System.out.println("Could not connect to the host!"); return; } System.out.println("Successfully connected to the server!"); System.out.println("Select from the options below:\n1: Check schedules\n2: Check pilots shifts\n3: Check corresponding airplanes and food offered\n4: Possible pilot shift changes"); loop:do{ int command; socketOut.flush(); command = keyIn.nextInt(); socketOut.flush(); socketOut.writeInt(command); while (socketIn.hasNext()){ System.out.println(socketIn.nextLine()); } }while(keyIn.nextInt()!=0); System.out.println("Closing connection to server!"); }catch(IOException e){ e.printStackTrace(); } finally{ try{ if(socketIn!=null) socketIn.close(); if(socketOut!=null) socketOut.close(); if(connection!=null) connection.close(); } catch(IOException e){ System.err.println("Socket could not be closed!"); } } } } 

Le problème est que vous utilisez Scanner dans votre client. L’exécution se bloque sur socketIn.hasNext() , car

public boolean hasNext()

Renvoie true si ce scanner a un autre jeton dans son entrée. Cette méthode peut être bloquée en attendant que l’entrée soit analysée. Le scanner ne dépasse aucune entrée.

Le code procédera au cas où une nouvelle entrée ou un stream sous-jacent serait fermé (et nous ne le souhaitons pas). Vous devez avoir un moyen de connaître la fin de la transmission sans fermer le stream. Regardez ci-dessous pour très simple.

À la fin de chaque try-catch block de votre serveur, mettez

 socketOut.println("$$$"); 

Dans le client, déclarez socketIn comme BufferedReader et instancier comme

 socketIn = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

Dans le client, changez également votre loop boucle pour

 int command = keyIn.nextInt(); do { socketOut.flush(); socketOut.writeInt(command); Ssortingng line; while (!(line = socketIn.readLine()).equals("$$$")) System.out.println(line); } while ((command = keyIn.nextInt()) != 0); 

Cela corrigera également votre double vérification de keyIn.nextInt() . Dans votre code, vous l’appelez deux fois par boucle (sauf la première itération).