Socket servidor no envía datos
Publicado por antonio (5 intervenciones) el 02/04/2007 13:39:21
Buenas a todos,
En respuesta a Gonzalo que me comentó que subiera el código para que vieseís lo que hacía aquí lo teneís.
//En el servlet llamo a un thread en el método init, que va a crear un ServerSocket
public void init (ServletConfig config) throws ServletException
{
super.init (config);
thread_control = new SimpleThread ();
thread_control.start ();
}
// El método run del thread en el que llamo al ServerSocket
public void run () {
ServerSocket sock = ServidorSocket.CrearSocketServidor ();
while (true) {
System.out.println ("Creamos el socket Servidor");
socket = ServidorSocket.ServirSocketServidor (sock);
}
}
// Este es el código del ServerSocket
Socket Servidor
public static ServerSocket CrearSocketServidor() {
ServerSocket socket = null;
try
{
// Se crea un socket servidor atendiendo a un determinado puerto.
// Por ejemplo, el 35557.
// METEMOS EL PUERTO QUE NOS ASIGNEN
socket = new ServerSocket (35551);
} catch (Exception e){
e.printStackTrace();
}
System.out.println ("Esperando cliente");
return socket;
}
public static ServerSocket ServirSocketServidor(ServerSocket socket)
{
String pathxml = Conexiones.getPathXML ();
String pathlistados = Conexiones.getPathListados ();
try {
System.out.println("Entro para aceptar clientes");
Socket cliente = socket.accept();
System.out.println ("Conectado con cliente de " + cliente.getInetAddress());
// Se hace que el cierre del socket sea "gracioso". Esta llamada sólo
// es necesaria si cerramos el socket inmediatamente después de
// enviar los datos (como en este caso).
// setSoLinger() a true hace que el cierre del socket espere a que
// el cliente lea los datos, hasta un máximo de 10 segundos de espera.
// Si no ponemos esto, el socket se cierra inmediatamente y si el
// cliente no ha tenido tiempo de leerlos, los datos se pierden.
cliente.setSoLinger (true, 10);
ObjectInputStream entrada = new ObjectInputStream(cliente.getInputStream());
ObjectOutputStream buffer_salida = new ObjectOutputStream(cliente.getOutputStream());
String tipo = entrada.readUTF ();
System.out.println("tipo "+tipo);
if (tipo.equals ("login")) {
String usuario = entrada.readUTF ();
String password = entrada.readUTF ();
System.out.println("SERVIDOR SOCKET El usuario "+usuario+" y el password "+password);
// REALIZO LAS OPERACIONES NECESARIAS
buffer_salida.writeInt (10);
}
}
}
entrada.close ();
buffer_salida.close ();
System.out.println("Acabado todo con EXITO");
} catch (IOException ioe) {
System.out.println ("IOException: "+ioe);
} catch (ClassNotFoundException cnfe) {
System.out.println ("ClassNotFoundException: "+cnfe);
}
return socket;
}
//Cliente Socket, llamado para pasar el nombre y el password
public ClienteSocket(String nom, String pass) throws UnknownHostException, IOException {
try
{
System.out.println("Entro en ClienteSocket con nombre y password");
this.s = new Socket ("localhost", 35551);
this.usuario = nom;
this.password = pass;
this.ServirCliente (this.s,nom,pass);
} catch (UnknownHostException ex){
System.out.println ("Error UnknownHostException "+ex.getMessage ());
ex.printStackTrace();
} catch (IOException ex){
System.out.println ("Error IOException "+ex.getMessage ());
ex.printStackTrace();
}
}
/**
* Crea el socket cliente y lee los datos
*/
public static void ServirCliente(Socket soc, String nom, String pass)
//public static void ServirCliente(Socket soc, String nom)
{
try
{
String path = Conexiones.getPathXML ();
OutputStream os = soc.getOutputStream();
ObjectOutputStream salida = new ObjectOutputStream(os);
InputStream is = soc.getInputStream ();
ObjectInputStream entrada = new ObjectInputStream(is);
System.out.println ("el pass es "+pass);
if (pass == null) {
// Escribimos primero que enviamos el fichero para que el servidor reconozca el servicio
salida.writeUTF ("fichero");
System.out.println("nombre "+nom);
System.out.println("path "+path);
String fich = path+nom;
System.out.println ("Escribimos el fichero "+fich);
File fichero = new File(fich);
salida.writeObject (fichero);
} else {
salida.writeUTF ("login");
salida.writeUTF (nom);
salida.writeUTF (pass);
System.out.println("Leemos la entrada");
//String ent = entrada.readUTF ();
System.out.println("entrada obtenida "+entrada.readInt ());
}
System.out.println ("CORRECTO");
salida.close ();
entrada.close ();
//soc.close ();
}
catch (Exception e)
{
System.out.println("Excepcion "+e);
e.printStackTrace();
}
}
Pues bien como ya dije días atrás cuando ejecuto el cliente, efectivamente se conecta con el servidor, pero luego se queda sin hacer nada la apliación, se queda colgada, y como ya dije si desde el server socket no le paso ningún parametro al cliente funciona perfectamente, falla cuando en el ServerSocket pongo el writeInt.
¿Alguna idea?
Gracias.
En respuesta a Gonzalo que me comentó que subiera el código para que vieseís lo que hacía aquí lo teneís.
//En el servlet llamo a un thread en el método init, que va a crear un ServerSocket
public void init (ServletConfig config) throws ServletException
{
super.init (config);
thread_control = new SimpleThread ();
thread_control.start ();
}
// El método run del thread en el que llamo al ServerSocket
public void run () {
ServerSocket sock = ServidorSocket.CrearSocketServidor ();
while (true) {
System.out.println ("Creamos el socket Servidor");
socket = ServidorSocket.ServirSocketServidor (sock);
}
}
// Este es el código del ServerSocket
Socket Servidor
public static ServerSocket CrearSocketServidor() {
ServerSocket socket = null;
try
{
// Se crea un socket servidor atendiendo a un determinado puerto.
// Por ejemplo, el 35557.
// METEMOS EL PUERTO QUE NOS ASIGNEN
socket = new ServerSocket (35551);
} catch (Exception e){
e.printStackTrace();
}
System.out.println ("Esperando cliente");
return socket;
}
public static ServerSocket ServirSocketServidor(ServerSocket socket)
{
String pathxml = Conexiones.getPathXML ();
String pathlistados = Conexiones.getPathListados ();
try {
System.out.println("Entro para aceptar clientes");
Socket cliente = socket.accept();
System.out.println ("Conectado con cliente de " + cliente.getInetAddress());
// Se hace que el cierre del socket sea "gracioso". Esta llamada sólo
// es necesaria si cerramos el socket inmediatamente después de
// enviar los datos (como en este caso).
// setSoLinger() a true hace que el cierre del socket espere a que
// el cliente lea los datos, hasta un máximo de 10 segundos de espera.
// Si no ponemos esto, el socket se cierra inmediatamente y si el
// cliente no ha tenido tiempo de leerlos, los datos se pierden.
cliente.setSoLinger (true, 10);
ObjectInputStream entrada = new ObjectInputStream(cliente.getInputStream());
ObjectOutputStream buffer_salida = new ObjectOutputStream(cliente.getOutputStream());
String tipo = entrada.readUTF ();
System.out.println("tipo "+tipo);
if (tipo.equals ("login")) {
String usuario = entrada.readUTF ();
String password = entrada.readUTF ();
System.out.println("SERVIDOR SOCKET El usuario "+usuario+" y el password "+password);
// REALIZO LAS OPERACIONES NECESARIAS
buffer_salida.writeInt (10);
}
}
}
entrada.close ();
buffer_salida.close ();
System.out.println("Acabado todo con EXITO");
} catch (IOException ioe) {
System.out.println ("IOException: "+ioe);
} catch (ClassNotFoundException cnfe) {
System.out.println ("ClassNotFoundException: "+cnfe);
}
return socket;
}
//Cliente Socket, llamado para pasar el nombre y el password
public ClienteSocket(String nom, String pass) throws UnknownHostException, IOException {
try
{
System.out.println("Entro en ClienteSocket con nombre y password");
this.s = new Socket ("localhost", 35551);
this.usuario = nom;
this.password = pass;
this.ServirCliente (this.s,nom,pass);
} catch (UnknownHostException ex){
System.out.println ("Error UnknownHostException "+ex.getMessage ());
ex.printStackTrace();
} catch (IOException ex){
System.out.println ("Error IOException "+ex.getMessage ());
ex.printStackTrace();
}
}
/**
* Crea el socket cliente y lee los datos
*/
public static void ServirCliente(Socket soc, String nom, String pass)
//public static void ServirCliente(Socket soc, String nom)
{
try
{
String path = Conexiones.getPathXML ();
OutputStream os = soc.getOutputStream();
ObjectOutputStream salida = new ObjectOutputStream(os);
InputStream is = soc.getInputStream ();
ObjectInputStream entrada = new ObjectInputStream(is);
System.out.println ("el pass es "+pass);
if (pass == null) {
// Escribimos primero que enviamos el fichero para que el servidor reconozca el servicio
salida.writeUTF ("fichero");
System.out.println("nombre "+nom);
System.out.println("path "+path);
String fich = path+nom;
System.out.println ("Escribimos el fichero "+fich);
File fichero = new File(fich);
salida.writeObject (fichero);
} else {
salida.writeUTF ("login");
salida.writeUTF (nom);
salida.writeUTF (pass);
System.out.println("Leemos la entrada");
//String ent = entrada.readUTF ();
System.out.println("entrada obtenida "+entrada.readInt ());
}
System.out.println ("CORRECTO");
salida.close ();
entrada.close ();
//soc.close ();
}
catch (Exception e)
{
System.out.println("Excepcion "+e);
e.printStackTrace();
}
}
Pues bien como ya dije días atrás cuando ejecuto el cliente, efectivamente se conecta con el servidor, pero luego se queda sin hacer nada la apliación, se queda colgada, y como ya dije si desde el server socket no le paso ningún parametro al cliente funciona perfectamente, falla cuando en el ServerSocket pongo el writeInt.
¿Alguna idea?
Gracias.
Valora esta pregunta


0