Foro de elhacker.net

Programación => PHP => Mensaje iniciado por: LaThortilla (Effort) en 5 Mayo 2017, 02:02 am



Título: Ayuda con Sockets PHP y Java [RESUELTO]
Publicado por: LaThortilla (Effort) en 5 Mayo 2017, 02:02 am
buenos dias estoy intentando hacer una conexión por sockets desde php y haciendo de servidor con java. a continuacion les describo mas o menos lo que sucede:

FLUJO:
1 - Servidor Inicia
2- Cliente crea la conexion socket.
3- Cliente abre la conexion socket.
4 - Servidor recibe conexion;
5 - Cliente Envia mensaje "ping".
6- al intentar leer el Bufferd el servidor se queda esperando "no se que" (en la linea 42 del codigo java)  :huh: :huh: :huh:. (Este es mi problema)
7. el cliente se le agota el tiempo de espera y se genera excepción.
8. justo al cerrarse la conexión por el tiempo agotado el servidor lee el mensaje "ping".


Servidor Java:

Código
  1. package modelo.conexion;
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5.  
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8.  
  9.  
  10. public class Servidor extends Thread {
  11.  
  12.    private static Servidor instance;
  13.    public static final int PORT = 9901;
  14.    public static boolean on = true;
  15.    ServerSocket serverSocket = null;
  16.    Socket clientSocket = null;
  17.  
  18.  
  19.    private Servidor() {
  20.  
  21.    }
  22.  
  23.    @Override
  24.    public void run() {
  25.        try {
  26.            // Create the server socket
  27.            serverSocket = new ServerSocket(PORT, 1);
  28.  
  29.            while (on) {
  30.                // Wait for a connection
  31.                System.out.println("Servidor a la escucha...");
  32.                clientSocket = serverSocket.accept();
  33.  
  34.  
  35.                // get input and output streams
  36.                BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  37.                // PrintWriter output = new PrintWriter (clientSocket.getOutputStream(),true);
  38.  
  39.                DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
  40.  
  41.                //read data json
  42.                String data = input.readLine();
  43.  
  44.                //output.write(data);
  45.                output.writeBytes("OK");
  46.                output.flush();
  47.  
  48.                clientSocket.close();
  49.  
  50.            }
  51.        } catch (IOException ioe) {
  52.            Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ioe);
  53.        }
  54.    }
  55.  
  56.    public static synchronized Servidor getInstance() {
  57.        if (instance == null) {
  58.            instance = new Servidor();
  59.            instance.run();
  60.        }
  61.        return instance;
  62.    }
  63.  
  64. }
  65.  


Codigo Cliente PHP:
Código
  1. <?php
  2. $fp = stream_socket_client("tcp://127.0.0.1:9901", $errno, $errstr, 15);
  3. if (!$fp) {
  4.    echo "$errstr ($errno)<br />\n";
  5. } else {
  6.       $delimitador = "\n\n"; // -------- ESTA ES LA SOLUCION --------
  7. $mensaje = "ping".$delimitador;
  8.    fwrite($fp, $mensaje, strlen($mensaje));
  9.  
  10.    sleep(2);
  11.    while (!feof($fp)) {
  12.        echo fgets($fp, 1024);
  13.    }
  14.    fclose($fp);
  15. }
  16. ?>


Título: Re: SOLUCION AL PROBLEMA
Publicado por: LaThortilla (Effort) en 7 Mayo 2017, 01:44 am
Bueno despues de testear un rato ... resolvi el problema
....

Explico...

cuando se lee un buffert si lo lees todo habran bytes que no estarn disponibles entonces el servidor se queda esperando el siguiente byte hasta que el cliente envie mas informacion....

la solucion es simple agregar dos saltos de linea despues de cada envio de datos desde el cliente....