Java Server和C#客户端之间的套接字文件传输

时间:2018-09-25 04:12:02

标签: java c# sockets

我正在用Java创建一个TCP服务器,并在C#中创建一个TCP客户端。在我的Java服务器中,我可以接收文件并将其保存在服务器文件夹中。问题出在我的c#客户端上,该客户端未发送任何数据,因此服务器将文件保存为空。有什么问题的想法吗?这是C#客户端代码和Java服务器代码:

    public void up( String nombre) throws IOException{

        /*FileOutputStream fr = new FileOutputStream(ruta+nombre);
        InputStream is = socket.getInputStream();
        byte[] buffer = new byte[8192]; // or 4096, or more
        is.read(buffer, 0, buffer.length);
        fr.write(buffer, 0, buffer.length);*/

    DataOutputStream output;
    BufferedInputStream bis;
    BufferedOutputStream bos;

    byte[] receivedData;
    int in;
    //String nombre;

    try{
        while(true){
            //Buffer de 1024 bytes
         System.out.println(nombre);
        receivedData = new byte[1024];
        bis = new BufferedInputStream(socket.getInputStream());
        DataInputStream dis=new DataInputStream(socket.getInputStream());
        //Recibimos el nombre del archivo
        //nombre = nombre.substring(nombre.indexOf('\\')+1,nombre.length());
        nombre = new File(nombre).getName();

            System.out.println(nombre);

        //Para guardar archivo recibido

        bos = new BufferedOutputStream(new FileOutputStream("C:/FTP/"+nombre));
        while ((in = bis.read(receivedData)) != -1){
            bos.write(receivedData,0,in);
        }
        bos.close();
        dis.close();
        }
    }catch (Exception e ) {
        System.err.println(e);
    }


}

在这里使用c#客户端

 ----------C# CLIENT---------
 public void enviarArchivo(string ruta)
    {
        try
        {
            socket = new Socket(AddressFamily.InterNetwork,          SocketType.Stream, ProtocolType.Tcp);
            socket.Connect("localhost", 5000);
            IPAddress[] address = Dns.GetHostAddresses("localhost");
            Thread thread = new Thread(leerserver);
            thread.Start();
            MessageBox.Show(ruta);
            byte[] buffer;
            buffer = ASCIIEncoding.UTF8.GetBytes(ruta);

            socket.SendFile(ruta);



        } catch (SocketException sE)
        {
            MessageBox.Show("Error al crear el socket" + sE);
        }

    }

1 个答案:

答案 0 :(得分:0)

以下对我有用。我删除了服务器端(while(true))的无限循环,并进行了一些小的清理。您的代码基本上可以正常工作,但是看起来您在编辑过程中遗留下了一堆残酷的东西(while循环),您迷路了,没有仔细阅读代码。

我做了一个小小的更改以使用临时文件,因为我不想打扰在我的计算机上建立一个FTP目录。只需将对File.createTempFile的一次呼叫更改为您需要的任何内容即可。

public class ServerTest implements Runnable {

   ServerSocket server;
   Socket socket;

   public static void main( String[] args ) throws Exception {
      new Thread( new ServerTest() ).start();
      Thread.sleep( 100 ); // wait a bit for server to start
      clientUpload();
   }

   @Override
   public void run() {
      try {
         server = new ServerSocket( 7888, 0, InetAddress.getLocalHost() );
         socket = server.accept();
         up( "ServerTest" );
      } catch( IOException ex ) {
         Logger.getLogger( ServerTest.class.getName() ).log( Level.SEVERE, null, ex );
      }

   }

   public void up( String nombre ) throws IOException {
      BufferedInputStream bis = null;
      BufferedOutputStream bos = null;

      byte[] receivedData;
      int in;
      int total = 0;
      try {
         //Buffer de 1024 bytes
         System.out.println( nombre );
         receivedData = new byte[ 1024 ];
         bis = new BufferedInputStream( socket.getInputStream() );
         //Recibimos el nombre del archivo
         //Para guardar archivo recibido
         bos = new BufferedOutputStream( new FileOutputStream( 
                 File.createTempFile( nombre, ".test" ) ) );
         while( (in = bis.read( receivedData )) != -1 ) {
            bos.write( receivedData, 0, in );
            total += in;
         }
         System.err.println( "Total bytes uploaded: " + total );
      } catch( Exception e ) {
         System.err.println( e );
      } finally {
         if( bos != null ) bos.close();
         if( bis != null ) bos.close();
      }
   }

   private static void clientUpload() {
      try( Socket client = new Socket( InetAddress.getLocalHost(), 7888 );
           OutputStream outs = client.getOutputStream() ) 
      {
         System.err.println( "Sending data..." );
         byte[] data = "This is a test!".getBytes( "UTF-8" );
         outs.write( data, 0, data.length );
         System.err.println( "Data finished." );
      } catch( IOException ex ) {
         Logger.getLogger( ServerTest.class.getName() ).log( Level.SEVERE, null, ex );
      }
   }

}