Java-сокет Json - PullRequest
       4

Java-сокет Json

0 голосов
/ 14 декабря 2018

ОБНОВЛЕНО

У меня обновленный код после ответа, у меня одна проблема, теперь я ничего не получил:

Проблема :

Connexion cliente reçue.
Lancement du traitement de la connexion cliente
Exception in thread "Thread-1" java.lang.NullPointerException
    at cuisine.TimeServer.onResponseReceived(TimeServer.java:85)
    at cuisine.ClientProcessor.run(ClientProcessor.java:43)
    at java.base/java.lang.Thread.run(Thread.java:844)

Сервер времени: 85: Обратный вызов

  @Override
  public void onResponseReceived(String response) {
    // When the response is received from ClientProcessor
    // this method is called (by ClientProcessor).
    // Your response is the parameter String response.
    callback.onResponse(response);
  }

Процессор клиента: 43:

server.onResponseReceived(response);

Один клиент может подключиться, но я не могу получитьчто-нибудь: Json или текст.

Вот мой новый код Java:

Main.java:

   import cuisine.TimeServer.OnResponseReceivedListener;


public class main implements OnResponseReceivedListener {

   public static void main(String[] args) throws IOException {

        String host = "192.168.1.21";
        int port = 8080;

        TimeServer ts = new TimeServer(host, port);
        ts.open();
        System.out.println("------------Connected ! ------------");

   }

   @Override
   public void onResponse(String response) {
     doSomethingWith(response);
     System.out.println("REPONSE : ");
     System.out.println(response);

   }

   private void doSomethingWith(String response) {
         System.out.println("REPONSE : ");
         System.out.println(response);
   }


}

Я действительно не знаюкак использовать ответ сейчас, потому что sysout "RESPONSE" не находится в моей консоли TimeServer.java:

...
import cuisine.ClientProcessor.Server;


public class TimeServer implements Server {

  public interface OnResponseReceivedListener {
    void onResponse(String response);
  }

  private int port = 2345;
  private String host = "127.0.0.1";
  private ServerSocket server = null;
  private boolean isRunning = true;
  private OnResponseReceivedListener callback;

  public TimeServer() {
    try {
      server = new ServerSocket(port, 100, InetAddress.getByName(host));
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public TimeServer(String pHost, int pPort) {
    host = pHost;
    port = pPort;
    try {
      server = new ServerSocket(port, 100, InetAddress.getByName(host));
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void open() {

    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                while (isRunning == true) {

                  try {
                    Socket client = server.accept();

                    System.out.println("Connexion cliente reçue.");
                    ClientProcessor c = new ClientProcessor(client);
                    Thread t = new Thread(c);
                    // Don't forget to define the Server for ClientProcessor
                    c.addServer(TimeServer.this);
                    t.start();

                  } catch (IOException e) {
                    e.printStackTrace();
                  }
                }

                try {
                  server.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  server = null;
                }
              }
            });

    t.start();
  }

  @Override
  public void onResponseReceived(String response) {
    // When the response is received from ClientProcessor
    // this method is called (by ClientProcessor).
    // Your response is the parameter String response.
    callback.onResponse(response);
  }

  public void addOnResponseReceivedListener(OnResponseReceivedListener listener) {
    callback = listener;
  }

  public void removeOnResponseReceivedListener() {
    callback = null;
  }

  public void close() {
    isRunning = false;
  }
}

ClientProcessor.java:

public class ClientProcessor implements Runnable {

      public interface Server {
        void onResponseReceived(String response);
      }

      private Socket sock;
      private PrintWriter writer = null;
      private BufferedInputStream reader = null;
      public List<Dish> dish;
      // Your server instance
      private Server server;

      public ClientProcessor(Socket pSock) {
        this.sock = pSock;
      }

      public void run() {
        System.err.println("Lancement du traitement de la connexion cliente");

        boolean closeConnexion = false;
        while (!sock.isClosed()) {

          try {

            writer = new PrintWriter(sock.getOutputStream());
            reader = new BufferedInputStream(sock.getInputStream());

            String response = read();

            // report the response to TimeServer
            server.onResponseReceived(response);

            InetSocketAddress remote = (InetSocketAddress) sock.getRemoteSocketAddress();

            String debug = "";
            debug = "Thread : " + Thread.currentThread().getName() + ". ";
            debug += "Demande de l'adresse : " + remote.getAddress().getHostAddress() + ".";
            debug += " Sur le port : " + remote.getPort() + ".\n";
            debug += "\t -> Commande reçue : " + response + "\n";
            System.err.println("\n" + debug);

            String toSend = "";

            switch (response.toUpperCase()) {
              case "ORDER":
                toSend = "Dish";
                break;
              case "CLOSE":
                toSend = "Communication terminée";
                closeConnexion = true;
                break;
              default:
                toSend = "Commande inconnu !";
                break;
            }

            writer.write(toSend);
            writer.flush();

            if (closeConnexion) {
              System.err.println("COMMANDE CLOSE DETECTEE ! ");
              writer = null;
              reader = null;
              sock.close();
              break;
            }
          } catch (SocketException e) {
            System.err.println("LA CONNEXION A ETE INTERROMPUE ! ");
            break;
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }

      public void addServer(Server server) {
        this.server = server;
      }

      private void removeServer() {
        server = null;
      }

      // La méthode que nous utilisons pour lire les réponses
      private String read() throws IOException {
        String response = "";
        int stream;
        byte[] b = new byte[4096];
        stream = reader.read(b);
        response = new String(b, 0, stream);
        return response;
      }
    }

Спасибо, Бенджамин.

1 Ответ

0 голосов
/ 14 декабря 2018

Обновление (обновлено Main.java)

Обновление №2 (удалены статические методы из Main.java и используется объект Main)

Редактировать: (удален предыдущий ответ о сокетах)

Это ответ json, теперь я хочу использовать его в моем main: на другом классе в том же пакете.

Поскольку вы заявили, что вы получаете ответ от клиента, но вы не знаете, как манипулировать им в своем классе Main, тогда ваша проблема не всокеты.

Решение: используйте обратные вызовы :

  • ClientProcessor сообщит ответ на TimeServer.
  • TimeServer сообщит об этом ответе на Main.

Сообщите ClientProcessor о сервере и сообщите о получении ответа.

public class ClientProcessor implements Runnable {

  public interface Server {
    void onResponseReceived(String response);
  }

  private Socket sock;
  private PrintWriter writer = null;
  private BufferedInputStream reader = null;
  public List<Dish> dish;
  // Your server instance
  private Server server;

  public ClientProcessor(Socket pSock) {
    this.sock = pSock;
  }

  public void run() {
    System.err.println("Lancement du traitement de la connexion cliente");

    boolean closeConnexion = false;
    while (!sock.isClosed()) {

      try {

        writer = new PrintWriter(sock.getOutputStream());
        reader = new BufferedInputStream(sock.getInputStream());

        String response = read();

        // report the response to TimeServer
        server.onResponseReceived(response);

        InetSocketAddress remote = (InetSocketAddress) sock.getRemoteSocketAddress();

        String debug = "";
        debug = "Thread : " + Thread.currentThread().getName() + ". ";
        debug += "Demande de l'adresse : " + remote.getAddress().getHostAddress() + ".";
        debug += " Sur le port : " + remote.getPort() + ".\n";
        debug += "\t -> Commande reçue : " + response + "\n";
        System.err.println("\n" + debug);

        String toSend = "";

        switch (response.toUpperCase()) {
          case "ORDER":
            toSend = "Dish";
            break;
          case "CLOSE":
            toSend = "Communication terminée";
            closeConnexion = true;
            break;
          default:
            toSend = "Commande inconnu !";
            break;
        }

        writer.write(toSend);
        writer.flush();

        if (closeConnexion) {
          System.err.println("COMMANDE CLOSE DETECTEE ! ");
          writer = null;
          reader = null;
          sock.close();
          break;
        }
      } catch (SocketException e) {
        System.err.println("LA CONNEXION A ETE INTERROMPUE ! ");
        break;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  private void addServer(Server server) {
    this.server = server;
  }

  private void removeServer() {
    server = null;
  }

  // La méthode que nous utilisons pour lire les réponses
  private String read() throws IOException {
    String response = "";
    int stream;
    byte[] b = new byte[4096];
    stream = reader.read(b);
    response = new String(b, 0, stream);
    return response;
  }
}

Теперь перейдите к TimeServer и сообщите о Main (то же самое)процедура как и раньше).Вам также необходимо сообщить об ответе на Main при получении от ClientProcessor.

public class TimeServer implements Server {

  public interface OnResponseReceivedListener {
    void onResponse(String response);
  }

  private int port = 2345;
  private String host = "127.0.0.1";
  private ServerSocket server = null;
  private boolean isRunning = true;
  private OnResponseReceivedListener callback;

  public TimeServer() {
    try {
      server = new ServerSocket(port, 100, InetAddress.getByName(host));
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public TimeServer(String pHost, int pPort) {
    host = pHost;
    port = pPort;
    try {
      server = new ServerSocket(port, 100, InetAddress.getByName(host));
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void open() {

    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                while (isRunning == true) {

                  try {
                    Socket client = server.accept();

                    System.out.println("Connexion cliente reçue.");
                    Thread t = new Thread(new ClientProcessor(client));
                    // Don't forget to define the Server for ClientProcessor
                    t.addServer(TimeServer.this);
                    t.start();

                  } catch (IOException e) {
                    e.printStackTrace();
                  }
                }

                try {
                  server.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  server = null;
                }
              }
            });

    t.start();
  }

  @Override
  public void onResponseReceived(String response) {
    // When the response is received from ClientProcessor
    // this method is called (by ClientProcessor).
    // Your response is the parameter String response.
    callback.onResponse(response);
  }

  public void addOnResponseReceivedListener(OnResponseReceivedListener listener) {
    callback = listener;
  }

  public void removeOnResponseReceivedListener() {
    callback = null;
  }

  public void close() {
    isRunning = false;
  }
}

Наконец, заставьте ваш Main слушать TimeServer и сделайте что-нибудь, когда он получит ответ.

public class Main implements OnResponseReceivedListener {

  public static void main(String[] args) {
    Main application = new Main();
    TimeServer ts = application.createTimeServer();
    ts.addOnResponseReceivedListener(application);
    ts.open();
    System.out.println("------------Connected ! ------------");
  }

  @Override
  public void onResponse(String response) {
    doSomethingWith(response);
  }

  private void doSomethingWith(String response) {
    // Your logic for the response here...
  }

  private TimeServer createTimeServer() {
    String host = "192.168.43.178";
    int port = 8080;
    return new TimeServer(host, port);
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...