首页 > 解决方案 > Java 服务器和 C# 客户端之间的套接字文件传输

问题描述

我在 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);
        }

    }

标签: javac#sockets

解决方案


以下对我有用。我删除了您在服务器端 ( while(true)) 中的无限循环并进行了一些小的清理。您的代码基本上可以工作,但看起来您在编辑(那个while循环)时留下了一堆kruft并且您迷路了,没有仔细阅读代码。

我做了一个小改动来使用临时文件,因为我不想费心在我的计算机上创建一个 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 );
      }
   }

}

推荐阅读