Ver Mensaje Individual
  #1 (permalink)  
Antiguo 25/10/2013, 14:44
cesarobcn
 
Fecha de Ingreso: julio-2008
Mensajes: 11
Antigüedad: 15 años, 9 meses
Puntos: 0
Mantener coneccion abierta en servidor - coneccion cliente servidor

Hola a todos! ,he logrado establecer conexión entre el cliente y el servidor, el cliente le solicita al servidor la hora, minutos, etc. y el servidor devuelve esa info, en cliente tengo un bucle hasta que le digo 'salir', entonces la conexión (socket) del cliente se cierra, pero lo curioso es que el servidor tambien cierra sesion.
La idea es que el servidor SIEMPRE este 'esperando' nuevas peticiones, ya que podria ejecutar otra vez 'cliente' y el servidor deberia estar conectado..tengo un bucle infinito en el servidor.. pero tendria que tener otro bucle que me controle que el cliente cerro su sesion (socket.close()) pero que no cierre el servidor, les dejo el codigo.. echarle un vistazo porfi.. gracias!!


**CLIENTE
Código:
package cliente;

import java.io.*;
import java.net.*;
/**
 * @author Cesar
 */
public class Cliente {
    /**
     * @param args the command line arguments
     */
    static final String HOST ="localhost";
    static final int PUERTO=5000;
    
    public static void main(String[] args) 
    {
	String pedirDato;
	boolean infinitoC = true;
        
        InputStreamReader entrada = new InputStreamReader(System.in);
        BufferedReader teclado = new BufferedReader(entrada);
        try
        {
            Socket skCliente = new Socket(HOST, PUERTO);
            while(infinitoC)
            {
                // Pedir dato que se enviara al servidor
                System.out.print("Ingrese [HORA-MINUTO-SEGUNDO-HORAMINUTO-HORAMINUTOSEGUNDO] : ");
                pedirDato = teclado.readLine();
                if("SALIR".equals(pedirDato) || "salir".equals(pedirDato))
                {
                    infinitoC=false;
                    pedirDato="salir";
                }
                else
                {
                    //infoSalida -> informac. que sale del cliente ..va al servidor
                    OutputStream auxOut = skCliente.getOutputStream();
                    DataOutputStream infoSalida = new DataOutputStream(auxOut);
                    infoSalida.writeUTF(pedirDato);   // enviamos al Servidor el parametro recibido por consola

                    //recibo e imprimo en pantalla el msje q me envia el 'Servidor' en 
                    //infoEntrada -> informac. que ingresa al cliente
                    InputStream auxIn = skCliente.getInputStream();
                    DataInputStream infoEntrada = new DataInputStream(auxIn);
                    System.out.println("El servidor dice : "+infoEntrada.readUTF());
                }
            }
            skCliente.close();
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
    
}

**SERVIDOR
Código:
package servidor;
import java.io.*;
import java.net.*;
import java.util.GregorianCalendar;
/*
 * @author Cesar 
 */
public class Servidor 
{
    private static int PUERTO=5000;
    
    public static void main(String[] args) 
    {
        String horaSistema, op="";
	int hora, minuto, segundo, cliente=0;
	boolean infinito = true, skCl=true;
			
        try
        {
            ServerSocket skServidor = new ServerSocket(PUERTO);			// coneccion hecha con el cliente.
            System.out.println("Escuchando al Puerto "+PUERTO+" Esperando..");

            Socket skCliente = skServidor.accept();                         // aqui el prog. se detiene y espera(escucha) al prox cliente
            ++cliente;
            while(infinito)
            {	
                //recibo e imprimo en pantalla el msje q recibo de 'Cliente' en 
                //infoEntrada -> informac. que entra - ingresa al servidor
                InputStream auxIn = skCliente.getInputStream();
                DataInputStream infoEntrada = new DataInputStream(auxIn);	// se crea el objeto infoEntrada
                op=infoEntrada.readUTF();					//recibe el texto: “HORA” “MINUTO” “SEGUNDO” “HORAMINUTO” “HORAMINUTOSEGUNDO”

                System.out.println("El Cliente numero "+Integer.toString(cliente)+" me esta solicitando.."+op);
                
                GregorianCalendar datoTime = new GregorianCalendar();
                hora = datoTime.get(GregorianCalendar.HOUR_OF_DAY);
                minuto = datoTime.get(GregorianCalendar.MINUTE);
                segundo = datoTime.get(GregorianCalendar.SECOND);
                //--------------------------------------------------------------
                //Aqui validar el parametro que se recibe desde el cliente.
                switch(op)
                {
                    case "HORA":
                            op = "La hora actual es : "+hora;
                            break;
                    case "MINUTO":
                            op = "El minuto actual es : "+minuto;
                            break;
                    case "SEGUNDO":
                            op = "el segundo actual es : "+segundo;
                            break;
                    case "HORAMINUTO":
                            op = "La hora y el minuto actual es : "+hora+" : "+minuto;
                            break;
                    case "HORAMINUTOSEGUNDO":
                            op = "La hora el minuto y el segundo actual es : "+hora+" : "+minuto+" : "+segundo;
                            break;
                    case "salir" :
                            op = "saliendo";
                            break;
                    case "SALIR" :
                            op = "saliendo";
                            break;
                    default :
                            op = "Opcion incorrecta";
                            break;	
                }
                //envia RESPUESTA al cliente
                //infoSalida -> informac. que sale fuera del servidor
                OutputStream auxOut = skCliente.getOutputStream();			
                DataOutputStream infoSalida = new DataOutputStream(auxOut);     // se crea el objeto infoSalida
                infoSalida.writeUTF(op);
                //--------------------------------------------------------------
             }
             skCliente.close();  /// **** AQUI ESTA EL TEMA ..ESTO CIERRA LA CONECC AL CLIENTE
                        
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}
Gracias!!

Última edición por cesarobcn; 25/10/2013 a las 14:53