elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Arreglado, de nuevo, el registro del warzone (wargame) de EHN


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  ayuda con sockets en java
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: ayuda con sockets en java  (Leído 4,226 veces)
vincentlaw

Desconectado Desconectado

Mensajes: 11



Ver Perfil
ayuda con sockets en java
« en: 10 Diciembre 2010, 20:07 pm »

he estado haciendo un servidor y cliente para transferir archivos, para subir archivos del cliente al servidor funciona perfectamente, pero  a la inversa, me crea un archivo de 0 bytes y no se transfieren.

aqui esta mi codigo. espero que puedan ayudarme


cliente:
Código:

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author vLAW
 */
public class client2 {
 
  Socket  client= new Socket();
  Socket  client2= new Socket();
 DataOutputStream   out= null;
DataInputStream in=null ;
  FileInputStream origen=null;
  FileOutputStream pt=null ;
 
String[] lista = new String[100];

   ////////////////////////////////////////////////
public String[] direcciones(String direccion) {


     


if(direccion.equals("1")){//------------------------------------si es uno se hace la actualizacion de la carpeta
    try{
       
        client= new Socket("localhost",6800);
    out= new  DataOutputStream(client.getOutputStream());
    in= new  DataInputStream(client.getInputStream());
out.writeUTF("1");




boolean x=true;//este while, ca`tura los datos que provienen del servidor
int xx=0;
while(x){
lista[xx]=in.readUTF();
if(in.readUTF().equals("fin"))
x=false;
xx++;
}

    }
    catch(Exception e){System.out.println("no se pudo enviar el mensage de peticion");}
}
  //------------------------------------------------------------------------------
  //---------------------------------------------------si no se hace un envio a el servidor


 //------------------------------------------------------------------------------

return lista;
    }

public void subir(String direccion, String nombre){
 try{
  client= new Socket("localhost",6800);
  pt = (FileOutputStream)client.getOutputStream() ;//para transferencia de archivos

   origen  = new FileInputStream(direccion);//para transferencia de archivos (lo que se va a enviar al server)
out= new  DataOutputStream(client.getOutputStream());
out.writeUTF(nombre);
//System.out.println(in.readUTF());
    client.sendUrgentData(100);
byte[] buf = new byte[1024];
int len;
while ((len = origen.read(buf)) > 0 ){
pt.write(buf, 0, len);

}
pt.close();
origen.close();
client.close();


}catch(Exception e){
         System.out.println("no se pudo copiar el archivo");

}


}

public void descargar(String descarga, String opcion){
 
        try {
           
             client= new Socket("localhost",6800);

             out= new  DataOutputStream(client.getOutputStream());

            out.writeUTF(opcion);
            out.writeUTF(descarga);
        } catch (IOException ex) {
            System.out.println("no se pudo enviar el mensage");
        }


 try{

//ABRIMOS UN BUFER PARA DESCARGAR LO QUE EL CLIENTE NOS ESTÁ ENVIANDO


//CREAMOS LA INSTANCIA PARA ESCRIBIR EL ARCHIVO EN DISCO
FileOutputStream destino = new java.io.FileOutputStream("C:/descargas2/nuevo");


byte[] buf = new byte[1024];
int len;
out.writeUTF("envia algo!!!!!!!!!!!!!!!!11");

while ((len = in.read(buf)) != -1) {
     System.out.println("carajo");
destino.write(buf, 0, len);
 
 
}


in.close();
destino.close();

        }
catch(Exception b){System.out.println("no se pudo copiar el archivo");}





    }
}




servidor
Código:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Servidor {//implements Runnable
ServerSocket server;
DataOutputStream out;
DataInputStream mensage;
String eleccion;
Socket client= new Socket();
String directorio;
FileOutputStream pt=null ;
 FileInputStream origen=null;
public Servidor() {
try {
//CREAMOS EL SOCKET DEL SERVIDOR
server=new ServerSocket(6800);
System.out.println("Servidor corriendo...");
} catch(Exception e) {
System.out.println("Error al conectarse al puerto\n"+e);
System.exit(1);
}
}
 
public void run() {
   

while (true) {

try {
//ESPERA A QUE LLEGUE UN CLIENTE
client=server.accept();
out= new DataOutputStream(client.getOutputStream());/////////////////////////
  mensage= new DataInputStream(client.getInputStream());///////////////////////////
} catch(java.io.IOException e) {
System.out.println("No se pudo establecer conexión " + e.getMessage());
}

  try {////////////////////////////////////////
     
   
 
eleccion=mensage.readUTF();

 System.out.println(eleccion);

      }

    catch(Exception e) {
System.out.println("mierda1");
    }

//------------------------------------si es uno se hace la actualizacion de la carpeta
if(eleccion.equals("1")|| eleccion.equals("2"))
{
    if(eleccion.equals("1")){
informacion();
    }
    else{
       
        descarga();
   
    }
    }//----------------------------------------------------------------
 else//----------------------------------------------si no, es una carga de arhivo
{
carga();
    }

//--------------------------------------------------------------
   
}
}

public static void main(String a[]) {
Servidor servidor = new Servidor();
// Ponemos a correr nuestro hilo servidor
//new Thread(servidor).start();
servidor.run();

}

public void descarga(){
   
    String copiadirectorio;
   copiadirectorio=directorio;
    try{
        String archivo4=mensage.readUTF();
       
       directorio= directorio.concat("\\"+archivo4);
System.out.println(directorio);
    }
    catch(Exception e){
    System.out.println("no se pudo enviar el mensag de descarga");
    }
 
descargareal(directorio);

directorio=copiadirectorio;
}


//---------------------------------------------------------------en proceso

public void descargareal(String archivo ){
 
 


 try{
     
  client= new Socket("localhost",6800);
  pt = (FileOutputStream)client.getOutputStream() ;//para transferencia de archivos

   origen  = new FileInputStream(archivo);
out= new  DataOutputStream(client.getOutputStream());


    client.sendUrgentData(100);
   
byte[] buf = new byte[1024];
int len;

System.out.println(mensage.readUTF());

while ((len = origen.read(buf)) > 0 ){
pt.write(buf, 0, len);
 System.out.println(buf);
}
pt.close();
origen.close();
client.close();



}catch(Exception e){
         System.out.println("no se pudo copiar el archivo");

}


}

//---------------------------------------------------------------

public void carga(){
try{

//ABRIMOS UN BUFER PARA DESCARGAR LO QUE EL CLIENTE NOS ESTÁ ENVIANDO
InputStream in = client.getInputStream();
//CREAMOS LA INSTANCIA PARA ESCRIBIR EL ARCHIVO EN DISCO
FileOutputStream destino = new java.io.FileOutputStream("C:/descargas/"+eleccion);

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
destino.write(buf, 0, len);
}
in.close();
destino.close();

        }
catch(Exception b){System.out.println("no se pudo copiar el archivo");}


}



public void informacion(){
 try {
///--------------------------------se hicieron 2 for, por que si no el cliente solo recuperava el nombre del archivo yuno no, uno si y uno no y asi...
 File archivo= new File("C:/descargas/");
directorio= archivo.toString();

                 String []archivos = archivo.list();
         for(int x=0;x<archivo.list().length;x++){
         System.out.println(archivos[x]);
         out.writeUTF(archivos[x]);
         }
                 for(int x=1;x<archivo.list().length;x++){
         System.out.println(archivos[x]);
         out.writeUTF(archivos[x]);
         }

out.writeUTF("fin");

 }

    catch(Exception e) {
System.out.println("mierda2");
    }

}

}


si da algunos errores, es por que  son algunos datos que se obtenian de una interface que hice del net beans, pero solo son  numeros, "1","2", y el nombre del archivo


En línea

cruz_lazcano

Desconectado Desconectado

Mensajes: 3


Ver Perfil
Re: ayuda con sockets en java
« Respuesta #1 en: 23 Octubre 2012, 15:50 pm »

Hola amigo, tengo un problema muy parecido al tuyo, estoy tratando de desarrollar un cliente serveridor con sockets. desde el cliente quiero mandar un a imprimir un archivo, seleccionando la impresora local donde esta el sevidor.

me podrias orientar, como guardar el archivo, ya que puedo enviar el archivo pero no se como hacerlo para que el servidor me reconozca que tipo de archivo es. y de ahi queria imprimir,

HELP ME.

soy nuevo en java.
he estado leyendo, llevo ya dos semanas con desvelos y nda.. ya intente con otro lenguaje y me trabo en lo mismo.





En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
sockets bloqueados + java
Java
Ctesias 1 6,736 Último mensaje 5 Abril 2005, 03:57 am
por AnKeR
sockets + java?
Java
coolfrog 3 4,011 Último mensaje 23 Octubre 2005, 05:25 am
por coolfrog
Java: Sockets TCP
Java
BlaineMonkey 0 3,629 Último mensaje 6 Mayo 2010, 13:21 pm
por BlaineMonkey
Ayuda con mi codigo. (Enviar buffer de imagen de c++ a java)(SOCKETS)
Java
70N1 0 1,555 Último mensaje 18 Diciembre 2015, 16:59 pm
por 70N1
Ayuda con Sockets PHP y Java [RESUELTO]
PHP
LaThortilla (Effort) 1 2,730 Último mensaje 7 Mayo 2017, 01:44 am
por LaThortilla (Effort)
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines